代码之家  ›  专栏  ›  技术社区  ›  Xin Lok

如何使用核心图形填充swift中的三角形

  •  2
  • Xin Lok  · 技术社区  · 9 年前

    我无法使用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填充这个三角形?

    1 回复  |  直到 9 年前
        1
  •  2
  •   Martin R    9 年前

    要填充路径,请设置填充颜色并使用 kCGPathContextFill 。要填充和划动 路径,使用 kCGPathFillStroke 。此外,路径应为 关闭 用于填充:

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