在iOS中使用触摸绘制水平线或垂直线
问题描述:
我正在研究一个项目,我希望如果用户触摸沿水平方向移动,那么水平线应该绘制并且用户触摸沿垂直方向移动,然后垂直线应该绘制。请建议使用Swift的一些解决方案。 我在下面试过。但是这是免费的。在iOS中使用触摸绘制水平线或垂直线
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
let touch: AnyObject? = touches.first
let lastPoint = touch!.previousLocation(in: holderView)
path.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y))
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
let touch: AnyObject? = touches.first
let currentPoint = touch!.location(in: holderView)
path.addLine(to: CGPoint(x: currentPoint.x, y: currentPoint.y))
//Design path in layer
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.orange.cgColor
shapeLayer.lineWidth = 20.0
holderView.layer.addSublayer(shapeLayer)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
path=UIBezierPath()
}
答
试试这个。
class DrawingView: UIView {
var path = UIBezierPath()
var initialLocation = CGPoint.zero
var finalLocation = CGPoint.zero
var shapeLayer = CAShapeLayer()
override func awakeFromNib() {
super.awakeFromNib()
setupView()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView(){
self.layer.addSublayer(shapeLayer)
self.shapeLayer.lineWidth = 20
self.shapeLayer.strokeColor = UIColor.blue.cgColor
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let location = touches.first?.location(in: self){
initialLocation = location
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
if let location = touches.first?.location(in: self){
let dx = location.x - initialLocation.x
let dy = location.y - initialLocation.y
finalLocation = abs(dx) > abs(dy) ? CGPoint(x: location.x, y: initialLocation.y) : CGPoint(x: initialLocation.x, y: location.y)
path.removeAllPoints()
path.move(to: initialLocation)
path.addLine(to: finalLocation)
shapeLayer.path = path.cgPath
}
}
}
可以通过这个链接http://stackoverflow.com/questions/4669490/how-to-draw-line-on-touch-event –
什么,如果用户触摸屏幕,并创建一个曲线路径点数? –
太多未知数!你的代码说:“有一条更加缓慢的路径,当触摸开始时,跳到触摸位置,当触摸移动时,画线到新的位置并在新的子图层中显示结果,当触摸结束时,创建一个新的贝塞尔路径” 。子层逻辑看起来效率极低(创建数百个部分重复的子层),而且更复杂的路径创建似乎不必要地倒退,但除此之外。鉴于上述逻辑的解释,你能否澄清你想达到的目标? – Baglan