使用CGAffineTransform和PanGestureRecognizer旋转ImageView

时间:2017-03-28 14:43:50

标签: ios swift xcode uikit core-graphics

我正在尝试使用CGAffineTransform旋转我使用的ImageView。基本上,我想要发生的是每次x坐标增加时,我都希望ImageView再旋转一点。

我做了数学计算,我希望ImageView每1.6º轮换一次1 x-coordinate。这就是我目前在gesture recognizer函数中所拥有的:

@objc func personDragRecognizer(recognizer: UIPanGestureRecognizer) {

    let rotationAngle: CGFloat = 1.6

    let translation = recognizer.translation(in: rView)
    if let view = recognizer.view {
        view.center = CGPoint(x:view.center.x +  translation.x, y:view.center.y + translation.y)
        view.transform = CGAffineTransform(rotationAngle: rotationAngle)
    }
    recognizer.setTranslation(CGPoint.zero, in: rView)

    if recognizer.view?.center == CGPoint(x: 197.5, y: 232.5)  {
        PlaygroundPage.current.liveView = eeView
    }

问题在于rotates576º bc 1.6 times 360。并且它不会继续旋转它只做一次。我想让它不断旋转。

如果有人可以提供帮助,我们将非常感激。非常感谢提前!!

干杯, 西奥

1 个答案:

答案 0 :(得分:4)

我不确定我是否完全理解您尝试实施的功能。以下是负责图像旋转的UIView子类的示例。

class CustomView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)

        let panGR = UIPanGestureRecognizer(target: self, action: #selector(panGestureDetected(sender:)))
        self.gestureRecognizers = [panGR]
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var gestureBeginning: CGFloat = 0.0

    func panGestureDetected(sender: UIPanGestureRecognizer) {
        guard sender.numberOfTouches > 0 else { return }

        let touchPoint = sender.location(ofTouch: 0, in: self)

        switch sender.state {
        case .began:
            gestureBeginning = touchPoint.x
            print("gestureBeginning: \(gestureBeginning)")
        case .changed:
            let progress = touchPoint.x - gestureBeginning
            print("progress: \(progress)")
            let rotationAngle: CGFloat = 1.6 * progress
            let view = self.subviews[0]
            let rads =  rotationAngle * .pi / 180
            view.transform = CGAffineTransform(rotationAngle: rads)
        default:
            break
        }
    }
}

在操场上跑步:

let imageView = UIImageView(image: #imageLiteral(resourceName: "image.png"))
imageView.frame = CGRect(origin: CGPoint(x: 50.0, y: 50.0), size: CGSize(width: 150.0, height: 150.0))

let containerView = CustomView(frame: CGRect(origin: .zero, size: CGSize(width: 250.0, height: 250.0)))
containerView.addSubview(imageView)

PlaygroundPage.current.liveView = containerView
PlaygroundPage.current.needsIndefiniteExecution = true