根据行进方向旋转UIImageView

时间:2017-11-21 11:29:18

标签: swift uiimageview

我有一个UIImageView在屏幕上移动,但我希望图像旋转,使图像的顶部朝向运动方向。

func shootStar(backgroundImage: UIImageView){
    let screenSize = UIScreen.main.bounds
    let screenHeight = screenSize.height
    let screenWidth = screenSize.width
    let star = UIImage(named: "Shooting Star")
    let starView = UIImageView(image: star!)

    starView.frame = CGRect(x: -40,y: screenHeight*0.05, width: 38.5, height: 42.8)
    view.insertSubview(starView, aboveSubview: backgroundImage)

    let toPoint:CGPoint = CGPoint(x: screenWidth + 80, y: screenHeight*0.3)
    let fromPoint:CGPoint = CGPoint(x: -40, y: 40)
    let movement = CABasicAnimation(keyPath: "position")
    movement.isAdditive = true
    movement.fromValue = NSValue(cgPoint: fromPoint)
    movement.toValue = NSValue(cgPoint: toPoint)
    movement.duration = 5
    starView.layer.add(movement, forKey: "move")
}

1 个答案:

答案 0 :(得分:0)

你的困难可能与iOS不使用笛卡尔坐标但atan2函数确实有关。这是一个如何计算角度并使用变换在行进方向上对齐imageview的示例操场。我在这里使用UIView变换和动画,但相同的原理和坐标系统适用于CALayer和CAAnimations:

import PlaygroundSupport
import UIKit

class V: UIViewController {
    let imageView = UIImageView()
    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.image = UIImage(named: "arrow up.jpg")
        view.addSubview(imageView)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        imageView.sizeToFit()
        imageView.center = view.center
        let vector = CGVector(dx: 120, dy: 100)
        let angle = atan2(vector.dy, vector.dx) - 1.5 * CGFloat.pi
        print(angle/CGFloat.pi)
        let rotationMatrix = CGAffineTransform(rotationAngle: angle)
        self.imageView.transform = rotationMatrix
        UIView.animate(withDuration: 5) {
            self.imageView.center.x += vector.dx
            self.imageView.center.y += vector.dy
        }

    }
}

PlaygroundPage.current.liveView = V()