6.Swift 触摸实现缩放

6.Swift 触摸实现缩放

  • Swift 触摸实现缩放
    • 实现思路

实现思路

实现思路
- 1.可以通过触摸移动事件的监听,判断是否是两点触摸;
- 2.如果是,通过勾股定理算出两点之间的距离,并记录该值;
- 3.然后下次在移动过程中不断计算两点之间的距离,与上次记录的值做比较;
- 4.假定一个临界值,与上次比较的值大于或者小于这个临界值的时候,分别视为放大或者缩小;
- 5.然后通过CGAffineTransformRotate(t: CGAffineTransform, _ angle: CGFloat) -> CGAffineTransform方法计算出图片缩放后的CGAffineTransform属性;
- 6.最后把刚才计算好的CGAffineTransform值替换掉图片原来的UIView.transform值即可。

形变属性
UIView.transform: CGAffineTransform

缩放
CGAffineTransformScale(t: CGAffineTransform, _ sx: CGFloat, _ sy: CGFloat) -> CGAffineTransform

class ViewController: UIViewController {

    @IBOutlet weak var iv: UIImageView!

    // 记录最后一次触摸,两指之间的距离,如果为0.0,视为第一次触摸
    private var lastDistance:CGFloat = 0.0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.view.multipleTouchEnabled = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        NSLog("touchesBegan")
    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // 判断是否是两指触摸
        if(touches.count == 2){
            let touchesSet:NSSet = touches as NSSet;
            let p1:CGPoint = touchesSet.allObjects[0].locationInView(self.view);
            let p2:CGPoint = touchesSet.allObjects[1].locationInView(self.view);

            let xx = p1.x-p2.x
            let yy = p1.y-p2.y

            // 勾股定理算出两指之间的距离
            let currentDistance = sqrt(xx*xx+yy*yy)

            // 判断是否第一次触摸
            if(self.lastDistance==0.0){
                self.lastDistance = currentDistance
            }else{
                // 不是第一次触摸,则开始和上次的记录的距离进行判断
                // 假定一个临界值为5,差距比上次小5,视为缩小
                if(self.lastDistance-currentDistance > 5){
                    NSLog("缩小")
                    self.lastDistance = currentDistance
                    // 重新设置UIImageView.transform,通过CGAffineTransformScale实现缩小,这里缩小为原来的0.9倍
                    self.iv.transform = CGAffineTransformScale(self.iv.transform, 0.9, 0.9)
                }else if(self.lastDistance-currentDistance < -5){
                    //差距比上次大5,视为方法
                    NSLog("放大")
                    self.lastDistance = currentDistance
                    // 重新设置UIImageView.transform,通过CGAffineTransformScale实现放大,这里放大为原来的1.1倍
                    self.iv.transform = CGAffineTransformScale(self.iv.transform, 1.1, 1.1)
                }
            }
        }
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        NSLog("touchesEnded")
    }

}

你可能感兴趣的:(移动,swift)