我想从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)
ios - MKMarkerAnnotationView的图像被截断了-LMLPHP

最佳答案

我找到了解决办法!我只需将contentMode设置为scalespectfit,并将边界更改为所需图像的大小(40x40px)。
这是显示完整mkmarkernanotationview的代码。

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

这个页面帮助我找到了这个解决方案。

关于ios - MKMarkerAnnotationView的图像被截断了,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46145241/

10-10 22:51