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

时间:2015-12-11 11:21:19

标签: ios swift uibezierpath cashapelayer

我继续我的Swift作业,我已经盯着here(之前的Stack 溢出问题)。但我现在面临一个新问题。最后,我只需使用UIBezierPathCAShapeLayer使用下面的代码(在@ 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)

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

enter image description here

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

2 个答案:

答案 0 :(得分:2)

您似乎已复制/粘贴,忘记将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))

答案 1 :(得分:0)

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

你忘记了一些drawingLayer 2