如何快速设置路径的fillColor和strokColor

时间:2019-06-20 19:04:10

标签: swift uigraphicscontext mkmapsnapshotter

我正在使用MKMapSnapshotter获取特定区域的图像。

我使用UIGraphicsGetCurrentContext()在图像上绘制线条以显示多边形

我可以设置线条颜色,但无法为多边形设置填充颜色。

下面是代码

private func drawLineOnImage(snapshot: MKMapSnapshotter.Snapshot, coordinates: [CLLocationCoordinate2D]) -> UIImage {
    let image = snapshot.image

    UIGraphicsBeginImageContextWithOptions(getMapFrameSize(), true, 0)

    image.draw(at: CGPoint.zero)

    let context = UIGraphicsGetCurrentContext()
    context!.setLineWidth(2.0)
    context!.setStrokeColor(UIColor.red.cgColor)
    context!.move(to: snapshot.point(for: coordinates[0]))
    for i in 0...coordinates.count-1 {
        context!.addLine(to: snapshot.point(for: coordinates[i]))
        context!.move(to: snapshot.point(for: coordinates[i]))
    }
    context!.strokePath()
    context!.setFillColor(UIColor.green.cgColor)
    context!.fillPath()

    let resultImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return resultImage!
}

我该如何实现?

解决方案:

private func drawLineOnImage(snapshot: MKMapSnapshotter.Snapshot, coordinates: [CLLocationCoordinate2D]) -> UIImage {
    let image = snapshot.image

    UIGraphicsBeginImageContextWithOptions(getMapFrameSize(), true, 0)

    image.draw(at: CGPoint.zero)

    let context = UIGraphicsGetCurrentContext()!

    context.setLineWidth(2.0)
    context.setStrokeColor(annotationColor.cgColor)
    context.setFillColor(annotationColor.withAlphaComponent(0.5).cgColor)

    var coordinates = coordinates
    if let firstPoint = coordinates.first { context.move(to: snapshot.point(for: firstPoint)) }
    context.move(to: snapshot.point(for: coordinates[0]))
    coordinates.removeFirst()
    coordinates.forEach { context.addLine(to: snapshot.point(for: $0)) }

    context.drawPath(using: .fillStroke)
    context.fillPath()

    let resultImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return resultImage!
}

1 个答案:

答案 0 :(得分:1)

来自strokePathfillPath的文档

  

清除当前路径是调用此函数的副作用。

这意味着在调用strokePath之后,将清除路径,因此在您调用fillPath时便不会绘制

相反,您应该致电context!.drawPath(using: .fillStroke)