Подтвердить что ты не робот

Google maps iOS SDK: пользовательские значки, которые будут использоваться в качестве маркеров

В Android API есть очень удобный для этого класс, IconGenerator. Используя IconGenerator в своем приложении для Android, я могу легко сделать маркер, который:

  • - это простой прямоугольник с цветом моего выбора.
  • изменяет размер, чтобы сохранить текст любой длины.
  • НЕ информационное окно. Я хочу, чтобы сам маркер содержал текст, как показано на изображении ниже, из версии Android.

введите описание изображения здесь

// Android - problem solved with IconGenerator
IconGenerator iconGenerator = new IconGenerator(context);
iconGenerator.setStyle(IconGenerator.STYLE_GREEN); // or any other color
Bitmap iconBitmap = iconGenerator.makeIcon(myString);
Marker m = new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(iconBitmap))
                              .position(myLatLng);
map.addMarker(m); // map is a com.google.android.gms.maps.GoogleMap

Есть ли способ сделать что-то столь же простое, как это в iOS, используя Swift? Недавно был анонсирован iOS api, который позволяет "настроить маркер" , но я не вижу, как применить его к этому варианту использования.

// iOS (Swift) - I don't know how to create the icon as in code above
let marker = GMSMarker(position: myLatLng)
marker.icon = // How can I set to a rectangle with color/text of my choosing?
marker.map = map // map is a GMSMapView
4b9b3361

Ответ 1

Вот что я сделал

let marker = GMSMarker()

// I have taken a pin image which is a custom image
let markerImage = UIImage(named: "mapMarker")!.withRenderingMode(.alwaysTemplate)

//creating a marker view
let markerView = UIImageView(image: markerImage)

//changing the tint color of the image
markerView.tintColor = UIColor.red

marker.position = CLLocationCoordinate2D(latitude: 28.7041, longitude: 77.1025)

marker.iconView = markerView
marker.title = "New Delhi"
marker.snippet = "India"
marker.map = mapView

//comment this line if you don't wish to put a callout bubble
mapView.selectedMarker = marker

Выходной сигнал

введите описание изображения здесь

И мое изображение маркера было

введите описание изображения здесь

Вы можете изменить свой цвет в соответствии с вашими потребностями. Кроме того, если вы хотите что-то в rectange, вы можете просто создать простой маленький прямоугольный образ и использовать его, как я сделал выше, и изменить цвет вашей потребности.

Или, если вам нужен прямоугольник с текстом внутри него, вы можете просто создать небольшой UIView с некоторой меткой, а затем преобразовать это UIView в UIImage и сделать то же самое.

//function to convert the given UIView into a UIImage
func imageWithView(view:UIView) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

Надеюсь, что это поможет!

Ответ 2

Вот что я сделал для решения той же проблемы, с которой вы столкнулись.

Я добавил изображение ниже в мои активы изображения,

enter image description here

Теперь я добавил ниже метод в моем коде:

-(UIImage*)drawText:(NSString*)text inImage:(UIImage*)image
{
    UIFont *font = [UIFont boldSystemFontOfSize:11];
    CGSize size = image.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    NSDictionary *attributes = @{
                                 NSFontAttributeName : font,
                                 NSParagraphStyleAttributeName : paragraphStyle,
                                 NSForegroundColorAttributeName : [UIColor redColor]
                                 };
    CGSize textSize = [text sizeWithAttributes:attributes];
    CGRect textRect = CGRectMake((rect.size.width-textSize.width)/2, (rect.size.height-textSize.height)/2 - 2, textSize.width, textSize.height);
    [text drawInRect:CGRectIntegral(textRect) withAttributes:attributes];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

Теперь я вызвал этот метод при назначении значка для GMSMarker, например так:

marker.icon = [self drawText:@"$33.6" inImage:[UIImage imageNamed:@"icon-marker"]];

Это создаст значок изображения, как показано ниже:

enter image description here

Здесь я сохранил размер фонового изображения, как мне было нужно. Вы по-прежнему можете настроить его, чтобы настроить его в соответствии с размером текста и несколькими строками.

UPDATE

Обновлен код в Swift:

func drawText(text:NSString, inImage:UIImage) -> UIImage? {

        let font = UIFont.systemFont(ofSize: 11)
        let size = inImage.size

        //UIGraphicsBeginImageContext(size)
        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(inImage.size, false, scale)
        inImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let style : NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
        style.alignment = .center
        let attributes:NSDictionary = [ NSAttributedString.Key.font : font, NSAttributedString.Key.paragraphStyle : style, NSAttributedString.Key.foregroundColor : UIColor.black ]

        let textSize = text.size(withAttributes: attributes as? [NSAttributedString.Key : Any])
        let rect = CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height)
        let textRect = CGRect(x: (rect.size.width - textSize.width)/2, y: (rect.size.height - textSize.height)/2 - 2, width: textSize.width, height: textSize.height)
        text.draw(in: textRect.integral, withAttributes: attributes as? [NSAttributedString.Key : Any])
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return resultImage
}

Ответ 3

Я попытался переписать Mehul Thakkar ответ на Swift 3. Надеюсь, что это сработает для вас. Но действительно проще сделать пользовательское представление Dari.

func drawText(text:NSString, inImage:UIImage) -> UIImage? {

        let font = UIFont.systemFont(ofSize: 11)
        let size = inImage.size

        UIGraphicsBeginImageContext(size)

        inImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let style : NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
        style.alignment = .center
        let attributes:NSDictionary = [ NSFontAttributeName : font, NSParagraphStyleAttributeName : style, NSForegroundColorAttributeName : UIColor.red ]

        let textSize = text.size(attributes: attributes as? [String : Any])
        let rect = CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height)
        let textRect = CGRect(x: (rect.size.width - textSize.width)/2, y: (rect.size.height - textSize.height)/2 - 2, width: textSize.width, height: textSize.height)
        text.draw(in: textRect.integral, withAttributes: attributes as? [String : Any])
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return resultImage
    }

Ответ 4

Вы можете просто добавить пользовательский вид в качестве маркера в Карте Google.

let marker = GMSMarker(position: coordinate)
marker.iconView = view // Your Custom view here

Вы можете использовать imageView (для размещения этого оранжевого цвета) и надпись (для текста) над ней

Ответ 5

Вот Swift 5 версия Eridana Swift преобразования ответа Мехула Таккара.

func drawTextT(text:NSString, inImage:UIImage) -> UIImage? {

    let font = UIFont.systemFont(ofSize: 11)
    let size = inImage.size

    UIGraphicsBeginImageContext(size)

    inImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    let style : NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
    style.alignment = .center
    let attributes:NSDictionary = [ NSAttributedString.Key.font : font, NSAttributedString.Key.paragraphStyle : style, NSAttributedString.Key.foregroundColor : UIColor.red ]

    //let textSize = text.size(attributes: attributes as? [String : Any])
    let textSize = text.size(withAttributes: attributes as? [NSAttributedString.Key : Any] )

    let rect = CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height)
    let textRect = CGRect(x: (rect.size.width - textSize.width)/2, y: (rect.size.height - textSize.height)/2 - 2, width: textSize.width, height: textSize.height)
    text.draw(in: textRect.integral, withAttributes: attributes as? [NSAttributedString.Key : Any]  )

    let resultImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return resultImage
}

Ответ 6

Самый простой способ достичь, если у вас есть только 1 изображение:

 marker.icon = #imageLiteral(resourceName: "fault_marker")

1) В последнем XCode напишите marker.icon = "imageLiteral".

2) Двойной щелчок на значке фиктивного изображения появился только сейчас.

3) выберите желаемое изображение.