现在在学swift,之前说要和大家分享的小demo就是这个了,demo本身很简单,由于初学swift,可能有些代码写的不够规范,也请大家多多指教。。。
先看看效果图吧
实现起来也很简单,ui上没什么好说了,注意的一点就是要将image的isUserInteractionEnabled勾打上。实现上是先声明一个变量,判断触摸的是否是需要响应触摸事件的View,然后就是利用UIView的触摸事件,下面是代码
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch:AnyObject in touches {
let t:UITouch = touch as! UITouch
if t.view == myImage {
isTouch = true;
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if isTouch == true {
for touch:AnyObject in touches {
UIGraphicsBeginImageContext(myImage.frame.size)
myImage.image?.draw(in: myImage.bounds)
let t:UITouch = touch as! UITouch
let point = t.location(in: t.view)
let rect = CGRect(x:point.x - 10 ,y:point.y - 10, width: 20, height: 20)
UIGraphicsGetCurrentContext()!.clear(rect)
myImage.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouch = false
}
是不是很简单,有不明白的也可以看Demo,欢迎大家Star.