Setting a rotation point for CGAffineTransformMakeRotation Swift

后端 未结 2 1571
[愿得一人]
[愿得一人] 2020-12-15 11:59

I am using the code below to rotate UIImageViews to different angles.

self.imageOne.transform = CGAffineTransformMakeRotation(CGFloat(-rotation))
self.imageT         


        
2条回答
  •  时光说笑
    2020-12-15 12:24

    Here's a Swift 3 extension based off of mttcrp's answer. It took me a while to figure out that the CGPoint isn't a coordinate in the view, but rather a proportion. For example, if you rotated the view around the point CGPoint(x: 0.5, y: 1) it would rotate around the bottom center of the view. Hope this helps!

    extension UIView{
        func setAnchorPoint(anchorPoint: CGPoint) {
    
            var newPoint = CGPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y)
            var oldPoint = CGPoint(x: self.bounds.size.width * self.layer.anchorPoint.x, y: self.bounds.size.height * self.layer.anchorPoint.y)
    
            newPoint = newPoint.applying(self.transform)
            oldPoint = oldPoint.applying(self.transform)
    
            var position : CGPoint = self.layer.position
    
            position.x -= oldPoint.x
            position.x += newPoint.x;
    
            position.y -= oldPoint.y;
            position.y += newPoint.y;
    
            self.layer.position = position;
            self.layer.anchorPoint = anchorPoint;
        }
    }
    

    and you would use it like this:

    let view = UIView() //This could be anything that inherits from UIView
    view.setAnchorPoint(anchorPoint: CGPoint(x: 0.5, y: 1))
    

提交回复
热议问题