Reputation: 2519
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)
Upvotes: 1
Views: 1200
Reputation: 421
I can't get the drawHierarchy to work I just get back an empty image.
Upvotes: 0
Reputation: 2519
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.
Upvotes: 4