【发布时间】:2020-11-07 05:05:21
【问题描述】:
我下面的快速代码绘制了水平线的水平方式,其角度不变。像 x 轴一样思考。我想以完全相反的方式画一条线。想想y轴。线绘制在
bezier.addLine(to: CGPoint(x: point.x, y: startPoint!.y))
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var startPoint: CGPoint?
let shapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 4
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.blue.cgColor
return shapeLayer
}()
override func viewDidLoad() {
super.viewDidLoad()
imageView.backgroundColor = .systemOrange
imageView.layer.addSublayer(shapeLayer)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
startPoint = touch?.location(in: imageView)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard var touch = touches.first else { return }
if let predicted = event?.predictedTouches(for: touch)?.last {
touch = predicted
}
updatePath(in: imageView, to: touch)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
updatePath(in: imageView, to: touch)
let image = UIGraphicsImageRenderer(bounds: imageView.bounds).image { _ in
imageView.drawHierarchy(in: imageView.bounds, afterScreenUpdates: true)
}
shapeLayer.path = nil
imageView.image = image
}
}
private extension ViewController {
func updatePath(in view: UIView, to touch: UITouch) {
let point = touch.location(in: view)
guard view.bounds.contains(point) else { return }
let bezier = UIBezierPath()
bezier.move(to: startPoint!)
bezier.addLine(to: CGPoint(x: point.x, y: startPoint!.y))
shapeLayer.path = bezier.cgPath
}
}
【问题讨论】:
-
您发布的大部分代码与画线本身无关。请编辑您的帖子以包含所需的最少信息。关于您的问题:您可以使用
bezier.addLine(to: CGPoint(x: startPoint!.x, y: point.y))以垂直方式绘制线条。只需让坐标的 x 部分保持固定即可。
标签: swift uibezierpath cashapelayer cgpoint touchesbegan