Search code examples
iosobjective-cgoogle-mapsgoogle-maps-sdk-ios

create UIImage programmatically for show marker on google map?


In my app i integrated Google map sdk for iOS. iwant to show marker with sequence number on it.like this image The number of marker will be decided at run time so i can not simply put an mage for each marker, somehow i have to create it programmatically. I'v an image without sequence on it. my idea is to create an image using that image and write number on it while creating it. But don't know how. Any help would be appreciated.


Solution

  • Thanks to @knshn for giving me the link in comment. here is my solution

    -(UIImage *)getImage :(UIImage *)icon stop:(NSString *)stopNumber color:(UIColor *)color
    {
         // create label
         UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, icon.size.width,icon.size.height)];
         [label setText:stopNumber];
        [label setTextColor:color];
        [label setFont:[UIFont boldSystemFontOfSize:11]];
        label.textAlignment = NSTextAlignmentCenter;
         
         // use UIGraphicsBeginImageContext() to draw them on top of each other
         
         //start drawing
         UIGraphicsBeginImageContext(icon.size);
         
         //draw image
         [icon drawInRect:CGRectMake(0, 0, icon.size.width, icon.size.height)];
        
         //draw label
         [label drawTextInRect:CGRectMake((icon.size.width - label.frame.size.width)/2, -5, label.frame.size.width, label.frame.size.height)];
         
         //get the final image
         UIImage *resultImage  = UIGraphicsGetImageFromCurrentImageContext();
         
         UIGraphicsEndImageContext();
        return resultImage;
    }
    

    Use in Swift

    func getImage(_ icon: UIImage?, stop stopNumber: String?, color: UIColor?) -> UIImage? {
        // create label
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: icon?.size.width ?? 0.0, height: icon?.size.height ?? 0.0))
        label.text = stopNumber
        label.textColor = color
        label.font = FontFamily.Metropolis.semiBold.font(size: 15)
        label.textAlignment = .center
        
        //start drawing
        UIGraphicsBeginImageContext(icon?.size ?? CGSize.zero)
        
        //draw image
        icon?.draw(in: CGRect(x: 0, y: 0, width: icon?.size.width ?? 0.0, height: icon?.size.height ?? 0.0))
        
        //draw label
        label.drawText(in: CGRect(x: ((icon?.size.width ?? 0.0) - label.frame.size.width) / 2, y: -3, width: label.frame.size.width, height: label.frame.size.height))
        
        //get the final image
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        return resultImage
    }