Swift shapelayer设置填充颜色不起作用

时间:2017-06-20 07:34:29

标签: ios swift calayer cashapelayer quartz-core

我尝试用平行四边形路径填充shapelayer。

let shapeLayer = CAShapeLayer()

    shapeLayer.lineWidth = 2.0
    shapeLayer.fillColor = UIColor.blue.cgColor
    shapeLayer.strokeColor = UIColor.black.cgColor
    let path = CGMutablePath()
    let points: [CGPoint] = [CGPoint(x: 10, y: 10), CGPoint(x: 100, y: 20), CGPoint(x: 100, y: 100), CGPoint(x:10, y: 80)]
    for (index, point) in points.enumerated() {
        path.move(to: point)
        var line: CGPoint = .zero
        if index == points.count - 1 {
            line = points[0]
        } else {
            line = points[index+1]
        }
        path.addLine(to: line)
    }

    shapeLayer.path = path

   layer.addSublayer(shapeLayer)

但在屏幕上我只看到该平行四边形的黑色边框。我之前使用过填充shapelayers,它可以用于更困难的路径。任何人都可以建议我修复此错误。

1 个答案:

答案 0 :(得分:2)

你不需要每次都移动点。

    // ...

    path.move(to: points[0])

    for index in 0..<points.count {
        var point: CGPoint = .zero
        if index == points.count - 1 {
            point = points[0]
        } else {
            point = points[index+1]
        }
        path.addLine(to: point)
    }

    //...