0

を使用して特定の領域の画像を取得して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!
}
4

1 に答える 1