更新时间:2020-05-27
绘制文字覆盖物简介
Since 6.5.2 起iOS地图SDK支持文字覆盖物(BMKText)绘制。
绘制文字覆盖物(BMKText)
1添加文字覆盖物数据
Objective-C
Swift
BMKText *_textOverlay = [BMKText textWithCenterCoordinate:CLLocationCoordinate2DMake(40.005, 116.554) text:@“天安门”]; // 向地图View添加Overlay,需要实现BMKMapViewDelegate的-mapView:viewForOverlay:方法来生成标注对应的View [_mapView addOverlay:_textOverlay];
let coor = CLLocationCoordinate2D(latitude: 40.005, longitude: 116.554) /// 根据中心点和文本生成文字覆盖物 /// @param coord 文字覆盖物的地理坐标 /// @param text 文字覆盖物文字内容 let textOverlay: BMKText = BMKText(center: coor, text: “天安门”)! // 向地图窗口添加Overlay,需要实现BMKMapViewDelegate的-mapView:viewForOverlay:函数来生成标注对应的View // @param overlay 要添加的overlay mapView.add(textOverlay)
2实现代理方法生成对应的View(BMKTextView)
代码如下所示:
Objective-C
Swift
- (__kindof BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id<BMKOverlay>)overlay { if ([overlay isEqual:_textOverlay]) { BMKTextView *textView = [[BMKTextView alloc] initWithTextOverlay:_textOverlay]; textView.textColor = [UIColor redColor]; // 字体颜色 textView.backgroundColor = [UIColor colorWithRed:0 green:1 blue:0 alpha:0.3]; // 背景色 textView.fontSize = 12; // 字体大小 textView.textFontType = kBMKTextFontNormal; textView.textAlignment = NSTextAlignmentCenter; // 文字对齐方式 textView.textMaxLineWidth = 60; // 行宽 textView.textLineSpacing = 0.f; // 行间距 textView.textParagraphSpacing = 2; // 字符间距 textView.textLineBreakMode = NSLineBreakByCharWrapping; // 字符截断类型 return textView; } return nil; }
/// 根据overlay生成对应的BMKOverlayView /// - Parameters: /// - mapView: 地图View /// - overlay: 指定的overlay /// - Returns: 生成的覆盖物View func mapView(_ mapView: BMKMapView, viewFor overlay: BMKOverlay) -> BMKOverlayView? { if overlay.isKind(of: BMKText.self) { if overlay.isEqual(textOverlay) { let textOverlayView = BMKTextView(textOverlay: textOverlay) textOverlayView?.textColor = UIColor.red // 字体颜色 textOverlayView?.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 0.3) // 背景色 textOverlayView?.fontSize = 12 // 字体大小 textOverlayView?.textFontType = kBMKTextFontNormal textOverlayView?.textAlignment = NSTextAlignment.center // 文字对齐方式 textOverlayView?.textMaxLineWidth = 60 // 行宽 textOverlayView?.textLineSpacing = 0.0 // 行间距 textOverlayView?.textParagraphSpacing = 2 // 字符间距 textOverlayView?.textLineBreakMode = NSLineBreakMode.byCharWrapping // 字符截断类型 return textOverlayView } } return nil }
3运行程序
效果如下: