Reputation: 1
I can clearly see my line, with the right stroke color, and the line is being drawn correctly, but no matter what, the fill color stay white.
I have added this layer to another UIView
subclass (custom view )
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)
What else can I try ?
EDIT
here is how I create the path :
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()
Turns out if you don't close your line it will not color it, but my line describes a time series and my look like this :
As you can see I close the curve from the bottom, but, because of those triangle are open I can not put color under this line. It works only if I put a line that close all those triangles.
Any suggestions to get a simple time series line filled with a color ?
Upvotes: 1
Views: 2714
Reputation: 15238
The issue is with the bezierPath
, the start point
is getting shifted every time in the loop so path.close()
is not able to close
the path
correctly w.r.t the start point
. By removing unnecessary move's
it works fine as below,
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)
Output
Upvotes: 2
Reputation: 1
I figure it out, you do not have to move the path to the new point every new line you make, it moves there automatically.
so removing path.move(to: point2)
, solves the problem !
Thanks for the comments.
Upvotes: 1