How to make drawing on MKMapSnapshot faster?

73 Views Asked by At

I use the following function to draw polylines on a UIImage snapshot of a MKMapView. The function works, but it's too slow for my purposes. Is there anyway to speed things up?

func drawLineOnImageFromLocations(image: UIImage, snapshot: MKMapSnapshot,
                                  polylineLocations: [CLLocation], color: CGColor) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(image.size, true, 0)

    // draw original image into the context
    image.draw(at: CGPoint.zero)

    // get the context for CoreGraphics
    guard let context = UIGraphicsGetCurrentContext() else {
        return image
    }

    context.beginPath()
    context.setLineWidth(10)
    context.setStrokeColor(color)
    let coordinates = polylineLocations.map{$0.coordinate}
    var points = [CGPoint]()
    for coordinate in coordinates {
        let point = snapshot.point(for: coordinate)
        points.append(point)
    }
    context.addLines(between: points)
    context.strokePath()

    // get the image from the graphics context
    let resultImage = UIGraphicsGetImageFromCurrentImageContext()
    // end the graphics context
    UIGraphicsEndImageContext()

    return resultImage!
}
1

There are 1 best solutions below

0
mistakeNot On BEST ANSWER

turns out calling:

UIGraphicsBeginImageContextWithOptions(image.size, true, 0)

is a very expensive operation. If you can refactor your code to call it just once it will speed up things considerably.