how to fill triangle in swift using Core graphics

怎甘沉沦 提交于 2019-12-11 04:01:55

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/32547783/how-to-fill-triangle-in-swift-using-core-graphics

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!