ioscgaffinetransform

CGAffineTransform - anchor image to baseline?


I am expanding/reducing an image perfectly using CGAffineTransform, BUT it changes around the centre points of the image. I want to keep it fixed/anchored to the baseline? Is this possible? The image is displayed in a UIImageView.

    UIView.animate(withDuration: 0.0, animations: {
        // Sunrise
        let multiplierSunrise = CGFloat(self.sunriseTime/self.sunriseMax)
        var transformSunrise = CGAffineTransform.identity
        transformSunrise = transformSunrise.translatedBy(x: 0, y: (self.imageHeight*(1-(multiplierSunrise/2))-(self.imageHeight/2)))
        transformSunrise = transformSunrise.scaledBy(x: 1, y: 1*multiplierSunrise )
        self.sunriseView.transform = transformSunrise
    })

Solution

  • Transforms are applied around the view's layer's anchor point. This is the layer's bounds center by default, but you can move it, describing the desired anchor point in percentage terms. So if you want the transform to be applied around the bottom of the view, you could say:

    self.sunriseView.layer.anchorPoint = CGPoint(x:0.5, y:1)
    

    However, when you say that, the view itself will move! To prevent that, also move the view's center to compensate:

    self.sunriseView.center.y += self.sunriseView.bounds.height/2
    self.sunriseView.layer.anchorPoint = CGPoint(x:0.5, y:1)
    

    Here's an example where, having done that, I proceed to apply a y-axis scale transform. As you can see, we are holding the bottom steady:

    enter image description here