如何使用 Core graphics 在 swift 中填充三角形

how to fill triangle in swift using Core graphics

我无法使用 swift 填充路径三角形。 我用了下面的代码,划了一笔。

        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);

知道用什么来填充这个三角形 shape.fillColor 吗?

要填充路径,请设置填充颜色并使用 kCGPathContextFill。填充和描边 路径,使用 kCGPathFillStroke。另外,路径应该是 closed 填充它:

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);