ios - MKMarkerAnnotationView 有一个截断的图像

标签 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

最佳答案

我找到了解决方案!我只需将 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对我找到这个解决方案有很大帮助。

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

相关文章:

ios - 更改 NSLayoutConstraint 时的 SWIFT 动画

ios - 使用 UIActivityViewController 未将多个图像保存在照片库中

ios - 在 Swift 的 UITableViewCell 中设置图像

ios - 按下右栏按钮项目移动左栏按钮项目

ios - 为什么我在导航 Controller 以编程方式返回后看不到顶部栏

ios - 如何在 Swift 中将小数截断到 x 位

objective-c - 裁剪后的 UIImageView 在设备上显示错误

ios - 如何获取第一个和第二个对象

iphone - 核心数据错误 : _Unwind_Resume called from function _PFFaultHandlerLookupRow in image CoreData

ios - 'NSInternalInconsistencyException',原因 : 'containerView is required.'