在不调整大小的情况下将文本添加到GMSMapView

时间:2017-07-30 10:07:43

标签: ios swift google-maps-sdk-ios

我需要在我的GMSMapView中添加一些文本字符串,就像在这里解决上一个问题的问题一样(从UILabel获取UIImage,然后将GMSGroundOverlay与该图像一起添加为GMSMapView的图标),但我需要添加文本,这不会用户更改地图缩放时调整大小。

enter image description here enter image description here

您可以看到当用户更改地图的缩放时,我的标签也会更改字体大小,但我需要添加标签,其外观与街道名称相同 - 无需在缩放时调整大小。如何制作?

2 个答案:

答案 0 :(得分:1)

基于上述@BùiĐứcKhánh的答案,Swift4

import UIKit
import CoreLocation
import GoogleMaps

extension GMSMarker {
    convenience init(position: CLLocationCoordinate2D, text: String, backgroundColor: UIColor? = .white) {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
        label.isOpaque = false
        label.font = UIFont(name: "Arial", size: 14)
        label.textColor = .white
        label.backgroundColor = backgroundColor ?? .white
        label.textAlignment = .center
        //label.layer.borderWidth = 2.0
        //label.layer.borderColor = UIColor.black.cgColor
        //label.layer.masksToBounds = true
        //label.layer.cornerRadius = 50
        label.text = text
        self.init(position: position)
        icon = UIImage.imageFromView(label)
    }
}

 extension UIImage {
    class func imageFromView(_ view: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        view.layer.render(in: context)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

用法:

let marker = GMSMarker(position: CLLocationCoordinate2DMake(40.1, 25.5),
                            text: "Lorem ipsum",
                            backgroundColor: .green)
marker.map = self.mapView

答案 1 :(得分:0)

根据您的要求,为什么不使用GMSMarker而不是GMSGroundOverlay

此代码对我有用

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

添加标签标记

UILabel *label = [UILabel new];
label.text = @"Job";

label.opaque = NO;

label.font = [UIFont fontWithName: @"Arial" size: 14];
label.textColor = [UIColor blackColor];
label.backgroundColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentCenter;

label.layer.borderWidth = 2.0;
label.layer.borderColor = [UIColor blackColor].CGColor;
label.layer.masksToBounds = true;

label.layer.cornerRadius = 50;
label.frame = CGRectMake(0, 0, 100, 100);

GMSMarker *title = [GMSMarker markerWithPosition:centerPosition];
title.icon = [self imageWithView:label];
title.map = mapView;