1

I am getting image of certain area using MKMapSnapshotter.

I draw lines on the image using UIGraphicsGetCurrentContext() to show polygon,

I can set the lines colour but I am unable to set fill color to the polygon.

Below is the code

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!
}

How can I achieve this?

SOLUTION:

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!
}
Anirudha Mahale
  • 2,526
  • 3
  • 37
  • 57
  • Your code shows you correctly settings both the stroke color and the fill color. What is your actual issue? – rmaddy Jun 20 '19 at 19:06
  • I want both border color and fill color, but unfortunately I am only getting border color. If I comment my border color code then I get fill color. – Anirudha Mahale Jun 20 '19 at 19:08

1 Answers1

4

From the docs for strokePath and fillPath

The current path is cleared as a side effect of calling this function.

That means that after calling strokePath, the path is cleared so there is noting to draw when you call fillPath

Instead you should call context!.drawPath(using: .fillStroke)

Craig Siemens
  • 12,942
  • 1
  • 34
  • 51