MKMarkerAnnotationView有一个截断的图像

时间:2017-09-10 20:24:12

标签: ios swift uiimage mapkit mkannotationview

我想从MKMarkerAnnotationView获取UIImage但是使用以下代码截断图像(在顶部和底部,请参见屏幕截图)

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()

知道它被截断的原因吗?在Xcode调试器中,我可以看到图像已经在pinAnnotation中被截断了(在我使用UIGraphics之前...来获取UIImage)

enter image description here

2 个答案:

答案 0 :(得分:0)

我找到了解决方案!我只需要将contentMode设置为scaleAspectFit并将边界更改为我需要的图像大小(40x40px)。

这里是显示完整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()

此页面Demystifying iOS Layout帮助我找到了这个解决方案。

答案 1 :(得分:0)

我无法使drawHierarchy工作,我只是回到空图像。