如何围绕左上角的点旋转图像?

时间:2017-10-11 06:40:14

标签: ios swift rotation anchor

我有一个音乐播放器,我想在玩家正在播放时,图像在磁盘上。当播放器没有播放时,将图像围绕左上角的点旋转45°.heckImgView的约束为centerX to superView, top to superview = 40, size = (97,153)

我用Google搜索并找到以下代码:

func setAnchorPoint(_ anchorPoint:CGPoint, for view:UIView){

        let oldOrigin = view.frame.origin
        view.layer.anchorPoint = anchorPoint
        let newOrigin = view.frame.origin

        var transition = CGPoint()
        transition.x = newOrigin.x - oldOrigin.x
        transition.y = newOrigin.y - oldOrigin.y
        view.center = CGPoint(x: view.center.x - transition.x, y: view.center.y - transition.y)

    }

使用以下方法旋转图像:

if !player.isPlaying {
        setAnchorPoint(CGPoint(x:40 / 97.0,y:40 / 153.0), for: needleImgView) // I'm NOT SURE the 40 is right.
        //needleImgView.layer.anchorPoint = CGPoint(x:0,y:0)
        UIView.animate(withDuration: 0.5, animations: {
            self.needleImgView.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 4))
        }, completion: nil)

    }else{
        setAnchorPoint(CGPoint(x:40 / 97.0,y:40 / 153.0), for: needleImgView) 
        //needleImgView.layer.anchorPoint = CGPoint(x:0,y:0)
        UIView.animate(withDuration: 0.5, animations: {
            self.needleImgView.transform = .identity
        }, completion: nil)

    }

我设置setAnchorPoint(CGPoint(x:0 / 97.0,y:0 / 153.0), for: needleImgView)needleImgView.layer.anchorPoint = CGPoint(x:0,y:0),结果是左上角点也移开

  

Screen Shot For The Left-top Point Moving Away

如何解决? THX。

2 个答案:

答案 0 :(得分:0)

有两种方法可以解决它---

1-您必须按40更改0

setAnchorPoint(CGPoint(x:0 / 97.0,y:0 / 153.0), for: needleImgView);

更改守则----

setAnchorPoint(CGPoint(x:-10.0 / 97.0,y:0 / 153.0), for: YourImage)

为图片制作相同更改X中的值。

2-拍摄双倍大小的图像像时钟一样,你的指针将从中间开始像钟针一样,你可以在没有锚点的情况下旋转。但这是解决的坏方法。

先尝试一下。它会帮助你,或者让你感到自由。

答案 1 :(得分:-1)

您可以尝试CABasicAnimation

0.5 x的锚点意味着在宽度的中间,0的y意味着在高度的顶部。

    imageView.layer.anchorPoint = CGPoint.init(x: 0.5, y: 0)

    let basic = CABasicAnimation.init(keyPath: "transform.rotation")
    basic.fromValue = NSNumber.init(value: 0)
    basic.toValue = NSNumber.init(value: -(Double.pi / 4))
    basic.fillMode = kCAFillModeForwards
    basic.isRemovedOnCompletion = false
    imageView.layer.add(basic, forKey: nil)