IOS 触摸获取坐标点、缩放图片实例

丌官承
2023-12-01
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        println("began")
    }
    override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
        println("move")

        println((touches as NSSet).anyObject()?.locationInView(self.view))//移动时输出当前坐标

    }

    override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
        println("end")
    }

其中第一个touches:是触摸点坐标集合

还可以开启多点触摸

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

同时输出这两个点得坐标位置

    override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
        println("move")

//        println((touches as NSSet).anyObject()?.locationInView(self.view))
        for touch in (touches as NSSet){
            println(touch.locationInView(self.view))
        }

    }

缩放图片实例
在全局先定义一个浮点类型的变量,用来当做距离长度

    //定义最后一次的操作
    private var lastDistance:CGFloat = 0.0

在touchesMoved函数中

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
//        println("move")

//        println((touches as NSSet).anyObject()?.locationInView(self.view))

//        for touch in (touches as NSSet){
//            println(touch.locationInView(self.view))
//        }

        //缩放即判断两点移动前后的距离是变大变小
        if touches.count == 2{      //触摸点是否等于2
            var a = (touches as NSSet).allObjects[0].locationInView(self.view)              //第一个点
            var b = (touches as NSSet).allObjects[1].locationInView(self.view)                 //第二个点

            //计算x与y的差
            var xx = a.x - b.x
            var yy = a.y - b.y
            //c为两点间距离
            var c = sqrt(xx*xx+yy*yy)

            if lastDistance == 0.0{
                lastDistance = c        //lastDistance一开始初始化为0.0,所以把距离赋值给 lastDistance后进行再进行距离差距的比较
            }else{
                if lastDistance - c > 5{
                    println("缩小")
                    lastDistance = c
                    //图片的缩放
                    iv.transform = CGAffineTransformScale(iv.transform, 0.9, 0.9)
                }else if lastDistance - c < -5{
                    println("放大")
                    lastDistance = c

                    iv.transform = CGAffineTransformScale(iv.transform, 1.1, 1.1)
                }
            }

        }
    }
 类似资料: