如何在 UIView 中独立绘制到 CAShapeLayer?

How to draw to CAShapeLayer in a UIView independently?

我正在继续我的 Swift 作业 我已经盯着 (previous StackOverflow question). But I'm facing a new problem now. Finally I am able to draw dots on my river image just by using a UIBezierPath and a CAShapeLayer using the code below (with the help of @njuri):

import UIKit

let beginPoint = UIBezierPath(ovalInRect: CGRectMake(130, 360, 20, 20))
let endPoint = UIBezierPath(ovalInRect: CGRectMake(260, 57, 20, 20))

let drawingView = UIView.init(frame: CGRect(x: 0, y: 0, width: 640, height: 400))
drawingView.addSubview(UIImageView(image: UIImage(named: "River.jpeg")))

let drawingLayer = CAShapeLayer()
drawingLayer.path = beginPoint.CGPath
drawingLayer.strokeColor = UIColor.greenColor().CGColor
drawingLayer.lineWidth = 3
drawingLayer.fillColor = UIColor.whiteColor().CGColor

drawingView.layer.addSublayer(drawingLayer)

let drawingLayer2 = CAShapeLayer()
drawingLayer2.path = endPoint.CGPath
drawingLayer.strokeColor = UIColor.redColor().CGColor
drawingLayer.lineWidth = 3
drawingLayer.fillColor = UIColor.whiteColor().CGColor

drawingView.layer.addSublayer(drawingLayer2)

这里的问题是结果不是我预期的那样,正如您在下面看到的,我确实有两个点,但一个全黑(而不是红色边框和白色填充),另一个一个是绿色边框和白色填充(正如我想要的那样)

但是,为什么会发生这种情况?根据代码,我这里有两个单独的 CAShapeLayer,它们具有不同的属性,我将它们分别添加到 UIView

看起来您 copy/pasted 忘记将 drawingLayer 重命名为 drawingLayer2

let drawingLayer2 = CAShapeLayer()
drawingLayer2.path = endPoint.CGPath
drawingLayer2.strokeColor = UIColor.redColor().CGColor
drawingLayer2.lineWidth = 3
drawingLayer2.fillColor = UIColor.whiteColor().CGColor

因此,drawingLayer2 只是使用 strokeColorlineWidthfillColor

的默认值

您可以创建一个函数来简化您的代码。而不是复制和粘贴,后者容易出错。

func addDotWithPath(path: UIBezierPath) -> CAShapeLayer {
    let drawingLayer = CAShapeLayer()
    drawingLayer.path = path.CGPath
    drawingLayer.strokeColor = UIColor.greenColor().CGColor
    drawingLayer.lineWidth = 3
    drawingLayer.fillColor = UIColor.whiteColor().CGColor
    return drawingLayer
}

drawingView.layer.addSublayer(addDotWithPath(beginPoint))
drawingView.layer.addSublayer(addDitWithPath(endPoint))
let drawingLayer2 = CAShapeLayer()
drawingLayer2.path = endPoint.CGPath
drawingLayer.strokeColor = UIColor.redColor().CGColor
drawingLayer.lineWidth = 3
drawingLayer.fillColor = UIColor.whiteColor().CGColor

你只是忘记了一些 drawingLayer 2