ios - 我想在集群中加载 XIB 或 View 而不是 Apple Maps 中的图像
问题描述
我正在使用此代码创建一个集群,我正在获取带有数字的圆形图像。我想在集群视图而不是图像中加载 XIB。
我创建了一个名为 image() 的函数来创建带有数字的图像,但我需要显示一个视图。
这是我为此使用的两个类。
class UserAnnotationView: MKAnnotationView {
static let preferredClusteringIdentifier = Bundle.main.bundleIdentifier! + ".UserAnnotationView"
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
clusteringIdentifier = UserAnnotationView.preferredClusteringIdentifier
image = UIImage(named: "marker_default_yellow")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var annotation: MKAnnotation? {
willSet {
clusteringIdentifier = UserAnnotationView.preferredClusteringIdentifier
}
}
}
//MARK:- Clustering
class UserClusterAnnotationView: MKAnnotationView {
static let preferredClusteringIdentifier = Bundle.main.bundleIdentifier! + ".UserClusterAnnotationView"
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
collisionMode = .circle
updateImage()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var annotation: MKAnnotation? { didSet { updateImage() } }
private func updateImage() {
if let clusterAnnotation = annotation as? MKClusterAnnotation {
self.image = image(count: clusterAnnotation.memberAnnotations.count)
} else {
self.image = UIImage(named: "marker_default_yellow")//image(count: 1)
}
}
func image(count: Int) -> UIImage {
let bounds = CGRect(origin: .zero, size: CGSize(width: 45, height: 45))
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { _ in
// Fill full circle with tricycle color
UIColor.white.setFill()
UIBezierPath(ovalIn: bounds).fill()
// Fill inner circle with white color
kAppDefaultColor.setFill()
UIBezierPath(ovalIn: bounds.insetBy(dx: 1, dy: 1)).fill()
// Finally draw count text vertically and horizontally centered
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.white,
.font: UIFont(name: Constants.FontName.rubikRegular, size: 18) ?? UIFont()
]
let text = "\(count)"
let size = text.size(withAttributes: attributes)
let origin = CGPoint(x: bounds.midX - size.width / 2, y: bounds.midY - size.height / 2)
let rect = CGRect(origin: origin, size: size)
text.draw(in: rect, withAttributes: attributes)
}
}
}
解决方案
推荐阅读
- python - kivy python buttonbehavior on_press disable
- javascript - 如何使用角度替换删除逗号
- azure - 通过 SSL 将 myPHPAdmin (Azure) 连接到 MySqlb (Azure)
- php - 如何修复 laravel 安装失败,因为扩展未启用
- python - 在管理员中使用之前将字段转换为整数,按该字段排序
- mule - Anypoint studio 抛出 org.xml.sax.SAXParseException 错误
- reactjs - 如何在启动时将数据从数据库写入状态?
- android - 如何扫描原始资源?
- excel - 仅在文本框中的 VBA 数字
- delay - Quasar + AmCharts Redering 时间延迟