问题描述
我的快速代码的目标是使每条线只能以90度角放置。现在,代码有两个起点和终点,在触摸uiview时起点是固定的。我希望用户能够触摸一个点,并且只能以90度角延伸线。查看下面的gif以获取更多信息。底线是我要达到的目标。我认为您必须在开始使用警惕。
import UIKit
class ViewController2: UIViewController {
@IBOutlet weak var drawingPlace: UIImageView!
var startTouch : CGPoint?
var secondTouch : CGPoint?
var currentContext : CGContext?
var prevImage : UIImage?
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
let touch = touches.first
startTouch = touch?.location(in: drawingPlace)
}
override func touchesMoved(_ touches: Set<UITouch>,with event: UIEvent?) {
for touch in touches{
secondTouch = touch.location(in: drawingPlace)
if(self.currentContext == nil){
UIGraphicsBeginImageContext(drawingPlace.frame.size)
self.currentContext = UIGraphicsGetCurrentContext()
}else{
self.currentContext?.clear(CGRect(x: 0,y: 0,width: drawingPlace.frame.width,height: drawingPlace.frame.height))
}
self.prevImage?.draw(in: self.drawingPlace.bounds)
let bezier = UIBezierPath()
bezier.move(to: startTouch!)
bezier.addLine(to: secondTouch!)
bezier.close()
UIColor.blue.set()
self.currentContext?.setLineWidth(4)
self.currentContext?.addPath(bezier.cgPath)
self.currentContext?.strokePath()
let img2 = self.currentContext?.makeImage()
drawingPlace.image = UIImage.init(cgImage: img2!)
}
}
override func touchesEnded(_ touches: Set<UITouch>,with event: UIEvent?) {
self.currentContext = nil
self.prevImage = self.drawingPlace.image
}
}
解决方法
问题是这一行:
bezier.addLine(to: secondTouch!)
这使线条无论在哪里都遵循触摸的位置。取而代之的是,垂直于水平面放置一条线(我想这就是您所说的90度),然后将线添加到水平面上的该点。换句话说,使用x
的{{1}}组件,但使用secondTouch
的{{1}}组件作为y
组件。
y