Search code examples
iosswiftcalayeruiviewanimationcgaffinetransform

CGAffineTransform affects the corner radius of my UIView


I'm applying a CGAffineTransform animation to a UIView with the following code:

UIView.animate(withDuration: 0.5, delay: delay, options: [.autoreverse, .repeat], animations: {
    elementView.transform = CGAffineTransform(scaleX: 1.0, y: 0.4)
}) { (finished) in

}

The UIView scales correctly in the animation, but I also have the UIView's corner radius set to perfectly round the top and bottom of the view.

enter image description here

The problem is, when the scaling animation occurs, the corner radius of my UIView is "squished":

enter image description here

How can I ensure the corner radius remains perfectly rounded, while maintaining the scaling animation?


Solution

  • I think your best bet is to just change the frame property of elementView:

    UIView.animate(withDuration: 0.5, delay: delay, options: [.autoreverse, .repeat], animations: {
        elementView.frame = CGRect(x: elementView.frame.origin.x, y: elementView.frame.origin.y, width: elementView.frame.size.width, height: elementView.frame.size.height * 0.4)
    }) { (finished) in
    
    }
    

    or if you're using auto-layout:

    heightContraint.constant = heightConstraint * 0.4
    UIView.animate(withDuration: 0.5, delay: delay, options: [.autoreverse, .repeat], animations: {
        elementView.layoutIfNeeded()
    }) { (finished) in
    
    }
    

    Either way should keep your corner radius while shortening the view.