改变 CALayer 的大小也会改变之前添加层的大小

changing size of CALayer also changes size of previously added layer's size

我正在尝试使用此客户 class 绘制 UIImageView,我希望能够更改用户绘制的线条的大小和颜色。但是每次我改变 CALayer 的大小或颜色之前添加的层的颜色和大小也会随之改变。

class DrawingImageView: UIImageView {
private lazy var path = UIBezierPath()
private lazy var previousTouchPoint = CGPoint.zero
var strokeColor: CGColor!
var strokeWidth: CGFloat!

override init(frame: CGRect) {
    super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)

    let shapeLayer = CAShapeLayer()
    shapeLayer.lineWidth = strokeWidth ?? 4
    shapeLayer.strokeColor = strokeColor ?? UIColor.black.cgColor
    shapeLayer.lineCap = .round
    shapeLayer.lineJoin = .round
    layer.addSublayer(shapeLayer)


    if let location = touches.first?.location(in: self) { previousTouchPoint = location }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesMoved(touches, with: event)
    
    if let location = touches.first?.location(in: self) {
        path.move(to: location)
        path.addLine(to: previousTouchPoint)
        previousTouchPoint = location

        let layerA = layer.sublayers?.last as! CAShapeLayer

        layerA.path = path.cgPath
    }
  }
}

这就是我将 class 分配给 tempImageView

的方式
    let mainImageView = UIImageView()
    var tempImgView: DrawingImageView?

    mainImageView.frame = CGRect(x: 0, y: self.view.bounds.height / 7, width: imageWidth, height: imageHieght)
    mainImageView.contentMode = .scaleAspectFit
    mainImageView.layer.zPosition = 2
    mainImageView.isOpaque = false
    mainImageView.backgroundColor = .clear
    mainImageView.isUserInteractionEnabled = true
    mainImageView.tintColor = .clear
    self.view.addSubview(mainImageView)

    func DrawOverImage() {
    
    mainImageView.isHidden = true
    let drawnImageView = DrawingImageView(frame: mainImageView.frame)

    drawnImageView.image = mainImageView.image
    drawnImageView.contentMode = .scaleAspectFit
    drawnImageView.isUserInteractionEnabled = true
    drawnImageView.layer.zPosition = 3
    self.tempImgView?.isUserInteractionEnabled = true
    self.tempImgView = drawnImageView

    self.view.addSubview(tempImgView!)
}

我也尝试创建 CAShapeLayers 数组并将层添加到数组然后分配替换子层,如 View.layer.subLayers[0] = layers[0] 但这也没有用,我找不到任何有用的在线资源。

非常感谢任何帮助或建议,谢谢。

那是因为您每次都在继续相同的路径,所以最新的笔触颜色和宽度会应用到整个路径。

不看你的其他逻辑,我相信你应该在你的 touchesBegan 中每次初始化一个新路径并且这个新路径应该在 touchesMoved

中使用

所以在 touchesBegan 中,尝试在 layer.addSublayer(shapeLayer) 之后添加 path = UIBezierPath(),看看这是否能满足您的需求