Search code examples
iosswiftuiimagemapkitmkannotationview

MKMarkerAnnotationView has a truncated image


I want to get a UIImage from a MKMarkerAnnotationView but with the following code the image is truncated (at the top and bottom, see the screenshot)

let newAnnotation = SimpleAnnotation(sourceCoordinate: annotation.coordinate, sourceTitle: "Hello", sourceSubtitle: "world")
let pinAnnotation = MKMarkerAnnotationView(annotation: newAnnotation, reuseIdentifier: "Test")
pinAnnotation.markerTintColor = UIColor.red
pinAnnotation.glyphText = "1"
pinAnnotation.animatesWhenAdded = false
pinAnnotation.glyphTintColor = UIColor.white
pinAnnotation.titleVisibility = .hidden
pinAnnotation.subtitleVisibility = .hidden

UIGraphicsBeginImageContextWithOptions(pinAnnotation.bounds.size, false, 0.0)
pinAnnotation.drawHierarchy(in: CGRect(x:0,
                                       y:0,
                                       width:pinAnnotation.bounds.width,
                                       height:pinAnnotation.bounds.height),
                            afterScreenUpdates: true)
let snapshotImageFromMyView = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Any idea why it's truncated? In the Xcode debugger I can see the image is already truncated in the pinAnnotation (before I use UIGraphics... to get the UIImage)

enter image description here


Solution

  • I have found the solution! I have just to set the contentMode to scaleAspectFit and to change the bounds to the size of the image I need (40x40px).

    Here's the code displaying the full MKMarkerAnnotationView.

    let pinAnnotation = MKMarkerAnnotationView()
    pinAnnotation.markerTintColor = UIColor.red
    pinAnnotation.glyphText = "1"
    pinAnnotation.animatesWhenAdded = false
    pinAnnotation.glyphTintColor = UIColor.white
    pinAnnotation.titleVisibility = .hidden
    pinAnnotation.subtitleVisibility = .hidden
    pinAnnotation.contentMode = .scaleAspectFit
    pinAnnotation.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
    
    UIGraphicsBeginImageContextWithOptions(pinAnnotation.bounds.size, false, 0.0)
    pinAnnotation.drawHierarchy(in: CGRect(x:0,
                                           y:0,
                                           width:pinAnnotation.bounds.width,
                                           height:pinAnnotation.bounds.height),
                                afterScreenUpdates: true)
    let snapshotImageFromMyView = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    

    This page Demystifying iOS Layout has helped me a lot to find this solution.