【问题标题】:What's the best way to move a UIBezierPath stroke in Swift 4?在 Swift 4 中移动 UIBezierPath 笔划的最佳方法是什么?
【发布时间】:2017-12-09 19:13:37
【问题描述】:

我正在尝试实现一个可以使用 UIBezierPath 笔划在 Swift 4 中更改位置的光标。目前,我有一个函数,它有一个参数位置,其中包含“光标”的新 x 和 y 位置。我想将此位置参数用作 UIView 中光标的新位置。每次调用该函数时,我当前的实现都会呈现另一个光标。有没有办法改变 UIBezierPath 的一个实例的位置?请参阅下面的示例代码以供参考。

private var cursor:UIBezierPath = UIBezierPath()

public func changeCursorLocation(location: ScreenCoordinates) {
    self.cursor = UIBezierPath()

    UIColor.black.setStroke()
    self.cursor.lineWidth = 2

    self.cursor.move(to: CGPoint(x: location.x, y: location.y))
    self.cursor.addLine(to: CGPoint(x: location.x + 100, y: location.y)) // change if staff space changes
    self.cursor.stroke()
}

【问题讨论】:

    标签: ios swift ipad core-graphics swift4


    【解决方案1】:

    将光标绘制为CAShapeLayer 对象。这使您可以移动光标而无需重新绘制它。

    class MyView: UIView {
        let cursor = CAShapeLayer()
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setup()
        }
    
        func setup() {
            // Draw cursor and add it to this view's layer
            let path = UIBezierPath()
            path.move(to: .zero)
            path.addLine(to: CGPoint(x: 100, y: 0))
    
            cursor.path = path.cgPath
            cursor.strokeColor = UIColor.black.cgColor
            cursor.lineWidth = 2
    
            layer.addSublayer(cursor)
    
            changeCursorLocation(location: CGPoint(x: 50, y: 100))
        }
    
        func changeCursorLocation(location: CGPoint) {
            cursor.position = location
        }
    }
    

    【讨论】:

    • 您好,我刚刚尝试实现这一点,但是每当我更改 CAShapeLayer 的位置时,光标就会消失。我忘了提到这是在扩展 UIView 的类中实现的。我在 UIView 的 draw() 函数中调用 setup() 函数。
    • setup() 应该只调用一次 - 绘制光标形状。从那时起,您只需要更改光标的位置。你不需要 draw() 函数,你绝对不应该在其中调用 setup() 。什么时候需要改变光标位置?
    • 我只调用了一次 setup(),我也在 init 函数中尝试过,但调用 changeCursorLocation() 后形状仍然消失。每次单击按钮时光标都会改变位置,从而改变其位置
    • 需要初始化?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let loc = ScreenCoordinates(x: 100, y: 100) setupCursor(location: loc) changeCursorLocation(location: CGPoint (x: 120, y: 100)) }
    • init() 是放置 setup() 的正确位置。 draw() 方法仅用于自定义绘图代码。一旦您添加了 CAShapeLayer 的路径并将 CAShapeLayer 添加到视图层,光标就会显示出来。注释掉 draw() 方法,因为它正在重绘视图的层,覆盖光标子层。
    【解决方案2】:

    您可以从 0,0 开始创建 Bezier 路径,然后在绘制之前将 x/y 平移变换应用于绘图上下文。详细信息取决于您的绘图方式(您发布的代码是从视图的draw(rect:) 方法调用的吗?)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      相关资源
      最近更新 更多