Xin Lok
Xin Lok

Reputation: 529

how to fill triangle in swift using Core graphics

I am not able to fill a path triangle using swift. I used the following code, which make a stroke.

        let view = UIView(frame: CGRectMake(0, 0, 300, 300))
        let shape = CAShapeLayer()
        view.layer.addSublayer(shape)
        shape.opacity = 0.5
        shape.lineWidth = 2
        shape.lineJoin = kCALineJoinMiter
        shape.strokeColor = UIColor(hue: 0.786, saturation: 0.79, brightness: 0.53, alpha: 1.0).CGColor
        shape.fillColor = UIColor(hue: 0.786, saturation: 0.15, brightness: 0.89, alpha: 1.0).CGColor


        let context = UIGraphicsGetCurrentContext()
        CGContextSetStrokeColorWithColor(context, shape.strokeColor);
        CGContextSetLineWidth(context, shape.lineWidth);
        CGContextMoveToPoint(context, 100, 100)
        CGContextAddLineToPoint(context, 150, 150)
        CGContextAddLineToPoint(context, 100, 200)
        CGContextAddLineToPoint(context, 100, 100)
        CGContextDrawPath(context, kCGPathStroke);

Any idea, what to use for filling this triangle by shape.fillColor?

Upvotes: 2

Views: 1444

Answers (1)

Martin R
Martin R

Reputation: 539965

To fill a path, set a fill color and use kCGPathContextFill. To both fill and stroke the path, use kCGPathFillStroke. Also, the path should be closed for filling it:

CGContextSetFillColorWithColor(context, ...)
CGContextMoveToPoint(context, 100, 100) // move to first point
CGContextAddLineToPoint(context, 150, 150) // line to second point
CGContextAddLineToPoint(context, 100, 200) // line to third point
CGContextClosePath(context) // line to first point and close path
CGContextDrawPath(context, kCGPathFill);

Upvotes: 2

Related Questions