CAShapeLayer填充颜色将保持白色

时间:2018-10-30 08:35:28

标签: swift uiview cashapelayer

我可以用正确的笔触颜色清楚地看到我的线条,并且线条已正确绘制,但是无论如何,填充颜色都保持白色。

我已将此层添加到另一个UIView子类(自定义视图)中

  let shapeLayer = CAShapeLayer()
    shapeLayer.frame=CGRect(x: 0, y: 0, width: (size?.width)!, height: size!.height)
    shapeLayer.path = path.cgPath //from my bezier path
    shapeLayer.fillColor = UIColor.red.cgColor
    shapeLayer.strokeColor = curveLineColor!.cgColor
    shapeLayer.lineWidth = 3.0
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round
    shapeLayer.lineCap = CAShapeLayerLineCap.round
    self.layer.addSublayer(shapeLayer)

我还能尝试什么?

编辑

这是我创建路径的方式:

 let path = UIBezierPath()
 var point1:CGPoint!
 var point2:CGPoint!
 var firstpoint:CGPoint!

 for i in 0..<curvePoints.count-1
 {
    point1 = curvePoints[i]
    point2 = curvePoints[i+1]

    point1.y=size!.height-point1.y
    point2.y=size!.height-point2.y


    path.move(to: point1)
    path.addLine(to: point2)

    if( i == 0 ) {firstpoint=point1}



 }

//close the path
path.move(to: point2)
path.addLine(to: CGPoint(x: frame.width, y: frame.height))
path.move(to: CGPoint(x: frame.width, y: frame.height))
path.addLine(to: firstpoint)

path.close()

如果不关闭行,结果不会为它上色,但是我的行描述了一个时间序列,我的样子是这样的:

enter image description here

如您所见,我从底部关闭了曲线,但是,因为那些三角形是开放的,所以我无法在该线下放置颜色。仅当我放置一条闭合所有这些三角形的线时,它才有效。

是否有任何建议获得一条用颜色填充的简单时间序列线?

2 个答案:

答案 0 :(得分:1)

问题出在bezierPath上,每次循环中起始point都会移位,因此path.close()无法close path正确地开始point。通过删除不必要的move's,它可以按以下方式正常工作,

let path = UIBezierPath()

let curvePoints = [
    CGPoint.init(x: 60, y: 280),
    CGPoint.init(x: 100, y: 60),
    CGPoint.init(x: 150, y: 200),
    CGPoint.init(x: 220, y: 100),
    CGPoint.init(x: 300, y: 280)
]
path.move(to: curvePoints.first!)

for i in 1..<curvePoints.count {
    path.addLine(to: curvePoints[i])
}
path.close()

let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.strokeColor = UIColor.green.cgColor
shapeLayer.lineWidth = 3.0
shapeLayer.lineJoin = CAShapeLayerLineJoin.round // OR kCALineJoinRound
shapeLayer.lineCap = CAShapeLayerLineCap.round // OR kCALineCapRound
self.view.layer.addSublayer(shapeLayer)

输出

enter image description here

答案 1 :(得分:1)

我已经弄清楚了,您不必在每次制作新线时都将路径移动到新点,它会自动移动到那里。

因此删除path.move(to: point2)可以解决问题! 感谢您的评论。