在iOS的Google地图上添加文本 - 在GMSMapView上书写

4

我想在GMSMapView中添加一些文本标签。当然,随着地图缩放,文本应该自动调整大小。在Google Map SDK中,我没有看到文本对象。那么我该如何实现呢?

2个回答

5

以下是我根据@Saxon的建议提出的解决方案,这是从我的项目中复制和粘贴的,所以您需要修改以适应您的需求。想法是将UILabel渲染成UIImage,然后使用该图像设置GMSGroundOverlay图标。然后它会自动调整大小。 GMSCoordinateBounds是由NorthEast和SouthWest点构建的,因此如果您想在点CenterX和CenterY处居中标签,则需要按如下计算。

  UILabel *label = [UILabel new];      
  label.opaque = NO;
  label.text = @"H";
  label.font = [UIFont fontWithName: @"Arial-BoldMT" size: Normalize(32)];
  label.textColor = [UIColor blueColor];
  label.frame = CGRectMake(0, 0, Normalize(140), Normalize(140));
  label.textAlignment = NSTextAlignmentCenter;

  CLLocationDegrees offset = Normalize(0.03);  // change size here
  CLLocationDegrees southWestY = centerY - offset;
  CLLocationDegrees southWestX = centerX - offset;
  CLLocationDegrees northEastY = centerY + offset;
  CLLocationDegrees northEastX = centerX + offset;

  CLLocationCoordinate2D southWest = CLLocationCoordinate2DMake(southWestY,southWestX);
  CLLocationCoordinate2D northEast = CLLocationCoordinate2DMake(northEastY,northEastX);
  GMSCoordinateBounds *overlayBounds = [[GMSCoordinateBounds alloc] initWithCoordinate:southWest coordinate:northEast];

  GMSGroundOverlay *overlay = [GMSGroundOverlay groundOverlayWithBounds:overlayBounds icon:[self imageWithView:label]];
  overlay.bearing = 0;
  overlay.map = self.mapView

- (UIImage *) imageWithView:(UIView *)view
{
  UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
  [view.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return img;
}

我想了解Normalize函数。你能详细描述一下吗?它是否用于更改地图缩放时标签的大小? - Bùi Đức Khánh
1
@KhánhBùiĐức只是我编写的一个辅助函数,用于调整iPad和iPhone的字体。请忽略它。 - etayluz

1
一些建议: 如果您希望在缩放时文本以像素为单位保持固定大小,可以在将文本放置在标记图像中的位置添加标记。 如果您希望在缩放时文本以米为单位保持固定大小,可以在将文本放置在地面叠加图像中的位置添加地面叠加。

我认为标记图像不会随着缩放而调整大小,是吗?我希望文本能够随着地图一起缩放。 - etayluz
1
在这种情况下,请使用地面覆盖图的第二个建议 - 这将随着地图一起调整大小。 - Saxon Druce

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接