【问题标题】:draw line using uibezierPath in a vertical way使用 uibezierPath 以垂直方式画线
【发布时间】: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


【解决方案1】:

实际上,您继续使用 startPoint 并尝试将线添加到同一个静态点...它如何将线添加到您当前所在的同一点...在静态 @ 时为 Y 添加一些值987654322@ position 位置添加行

 bezier.move(to: startPoint!)
  bezier.addLine(to: CGPoint(x: startPoint!.x, y: point.y))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2018-04-25
    相关资源
    最近更新 更多