UIKit Dynamics具有平移,旋转和捏合手势

时间:2017-07-06 12:32:06

标签: ios swift swift3 uikit-dynamics

我已将UIDynamics添加到imageview并使用了pan手势。它可以正常使用平移手势,但是当我应用捏手势时,它无法正常工作。它显示的是大图像视图,但是当我开始拖动时,它会更改为原始大小。

这是我的代码:

func handleAttachmentGesture(_ sender: UIPanGestureRecognizer) {
    let location = sender.location(in: emojiSuperView!)
    let boxLocation = sender.location(in: self)
    switch sender.state {
    case .began:
        print("Your touch start position is \(location)")
        print("Start location in image is \(boxLocation)")

        animator.removeAllBehaviors()

        let centerOffset = UIOffset(horizontal: boxLocation.x - self.bounds.midX, vertical: boxLocation.y - self.bounds.midY)
        attachmentBehavior = UIAttachmentBehavior(item: self, offsetFromCenter: centerOffset, attachedToAnchor: location)
        animator.addBehavior(attachmentBehavior)
    case .ended:
        print("Your touch end position is \(location)")
        print("End location in image is \(boxLocation)")

        animator.removeAllBehaviors()

        // 1
        let velocity = sender.velocity(in: emojiSuperView!)
        let magnitude = sqrt((velocity.x * velocity.x) + (velocity.y * velocity.y))

        if magnitude > ThrowingThreshold {
            // 2
            let pushBehavior = UIPushBehavior(items: [self], mode: .instantaneous)
            pushBehavior.pushDirection = CGVector(dx: velocity.x / 10, dy: velocity.y / 10)
            pushBehavior.magnitude = magnitude / ThrowingVelocityPadding

            self.pushBehavior = pushBehavior
            animator.addBehavior(pushBehavior)

            // 3
            let angle = Int(arc4random_uniform(20)) - 10

            itemBehavior = UIDynamicItemBehavior(items: [self])
            itemBehavior.friction = 0.2
            itemBehavior.allowsRotation = true
            itemBehavior.addAngularVelocity(CGFloat(angle), for: self)
            animator.addBehavior(itemBehavior)
        }
    default:
        attachmentBehavior.anchorPoint = sender.location(in: emojiSuperView!)
        break
    }
}


func recognizePinchGesture(sender: UIPinchGestureRecognizer)
{
    weak var dynamicItem: UIDynamicItem?
    // whatever your item is, probably a UIView
    dynamicItem = self
    let behavior = UIGravityBehavior(items: [dynamicItem!])
    let animator = UIDynamicAnimator(referenceView: emojiSuperView!)
    // or however you're getting your animator
    animator.addBehavior(behavior)
    sender.view!.transform = sender.view!.transform.scaledBy(x: sender.scale, y: sender.scale)
    animator.updateItem(usingCurrentState: self)
    self.animator.updateItem(usingCurrentState: self)
    sender.scale = 1
}

1 个答案:

答案 0 :(得分:0)

当用户执行任何变换事件时,将当前变换保存到全局变量。

之后,当平移开始时,使用UIAttachmentBehavior的动作属性在开始状态中指定新变换。

        attachmentBehavior.action = {
            self.attachmentBehavior.items[0].transform = self.aTransform
        }