How to dynamically draw image for button in iOS? - ios

This is the result I need to accomplish:
I need the icons with basic image: basket and additionally I need to put there UILabel with some text: once it is just a number, and once it is an amount to pay. Any ideas?

This is my example:
var image = UIImage(named: "cart")!
let text = "1 PLN"
UIGraphicsBeginImageContext(CGSizeMake(80, 50))
let context = UIGraphicsGetCurrentContext()
let label = UILabel(frame: CGRectZero)
label.text = text
label.font = UIFont.systemFontOfSize(10)
label.sizeToFit()
let width = max(label.frame.size.width + 10, 15)
let height = CGFloat(15)
CGContextSetFillColorWithColor(context, UIColor.greenColor().CGColor)
CGContextFillRect(context, CGRectMake(0, 0, image.size.width, image.size.height))
image.drawInRect(CGRectMake(80/2-50/2, 0, 50, 50))
let path = UIBezierPath(roundedRect: CGRectMake(75-width, 45-height, width, height), cornerRadius: 5)
path.lineWidth = 2
UIColor.redColor().setStroke()
UIColor.yellowColor().setFill()
path.stroke()
path.fill()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Center
let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(10.0), NSParagraphStyleAttributeName: paragraphStyle]
(text as NSString).drawInRect(CGRectMake(75-width, 45-height, width, height), withAttributes: attributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
The result is following:
Some examples for different text:

Related

UIImage With Color & Centered Text

I'm trying to add a convenience initialiser to the UIImage which will allow me to create an image with a given text centred in the middle, and given background color:
I've got the following code:
public convenience init?(color: UIColor, withText: String, withTextColor: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let label = UILabel()
label.text = withText
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 40)
label.textColor = withTextColor
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
This creates the image with the correct background color - I'm not sure how to embed the UILabel in the middle of the image though.
EDIT
Attributed strings know how to draw themselves, so you don't need a label. They also can tell you how big they are or even wrap to fit an available width. Here is playground that shows how to get an image from any attributed string:
import UIKit
import PlaygroundSupport
extension NSAttributedString {
func asImage(size: CGSize = .init(width: .max, height: .max)) -> UIImage {
UIGraphicsImageRenderer(bounds: boundingRect(with: size, options: [.usesLineFragmentOrigin], context: nil)).image { context in
self.draw(at: .zero)
}
}
}
let attributedString = NSAttributedString.init(string: "testing", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
let image = attributedString.asImage()
let imageView = UIImageView(image: image)
PlaygroundPage.current.liveView = imageView
Here is the convenience initialiser drawing white text in the centre of a red image:
convenience init?(letters: String) {
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center
let sizeOfImage = CGSize(width: 120, height: 120)
let font = UIFont(name: "Georgia", size: 50)!
let imageText = NSAttributedString(string: letters, attributes: [.font: font, .foregroundColor: UIColor.white, .paragraphStyle: style])
let textHight = font.lineHeight
let renderer = UIGraphicsImageRenderer(size: sizeOfImage)
let image = renderer.image { context in
UIColor.red.setFill()
context.fill(CGRect(origin: .zero, size: sizeOfImage))
imageText.draw(in: CGRect(origin: CGPoint(x: 0, y: (sizeOfImage.height - textHight) / 2), size: sizeOfImage))
}
self.init(cgImage: image.cgImage!)
}

Setting attributed label as navigation title

I am working on IOS using swift 4. I have to make the Navigation controller, with the center Aligned App title with Image at its left. But I am not getting how to attach image to its left. The attributed Image always goes to its right.
For this I am appending the string twice. below is the code
//Get image and set it's size
let image = UIImage(named: "user2")
let newSize = CGSize(width: 30, height: 30)
//Resize image
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image?.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let imageResized = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//Create attachment text with image
let attachment = NSTextAttachment()
attachment.image = imageResized
let attachmentString = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: "")
myString.append(attachmentString)
let strAttachment = NSAttributedString(string: "My Ios App" )
myString.append(strAttachment)
navLabel.attributedText = myString
self.navigationItem.titleView = navLabel
What I am getting is some thing like below image is on left
what I want :
I just want the image to be shown with the space between text and Image.
I want the image to be look good and nice. Text should be center vertically to the image. what is good way of achieving this ?.
Using this code you will get your output :
let navgationView = UIView()
let label = UILabel()
label.text = " My Ios App"
label.sizeToFit()
label.center = navgationView.center
label.textAlignment = NSTextAlignment.center
let image = UIImageView()
image.image = UIImage(named: "user")
let imageAspect = image.image!.size.width/image.image!.size.height
image.frame = CGRect(x: label.frame.origin.x-label.frame.size.height*imageAspect, y: label.frame.origin.y, width: label.frame.size.height*imageAspect, height: label.frame.size.height)
image.contentMode = UIViewContentMode.scaleAspectFit
navgationView.addSubview(label)
navgationView.addSubview(image)
self.navigationItem.titleView = navgationView
navgationView.sizeToFit()
Output:-
Hope it's helps.!!
If you want to adjust your attachment position you must use the attachment.bounds property and if you want to adjust the text vertical alignment you need to use NSAttributedString baselineOffset key
Update
Swift 3 code
let normalNameString = NSMutableAttributedString.init(string: "")
let attachment = NSTextAttachment()
attachment.image = imageHelper.pgImage(textValue: "PG-13")
attachment.bounds = CGRect(x: 0, y: 0, width: (attachment.image?.size.width)!, height: (attachment.image?.size.height)!)
normalNameString.append(NSAttributedString(attachment: attachment))
normalNameString.append(NSAttributedString(string: " My Ios App", attributes: [NSBaselineOffsetAttributeName :6]))
self.lblText.attributedText = normalNameString
Swift 4 code
let normalNameString = NSMutableAttributedString.init(string: "")
let attachment = NSTextAttachment()
attachment.image = imageHelper.pgImage(textValue: "PG-13")
attachment.bounds = CGRect(x: 0, y: 0, width: (attachment.image?.size.width)!, height: (attachment.image?.size.height)!)
normalNameString.append(NSAttributedString(attachment: attachment))
normalNameString.append(NSAttributedString(string: " My Ios App", attributes: [NSAttributedStringKey.baselineOffset :6]))
self.lblText.attributedText = normalNameString
Swift 5 Update
let normalNameString = NSMutableAttributedString.init(string: "")
let attachment = NSTextAttachment()
attachment.image = imageHelper.pgImage(textValue: "PG-13")
attachment.bounds = CGRect(x: 0, y: 0, width: (attachment.image?.size.width)!, height: (attachment.image?.size.height)!)
normalNameString.append(NSAttributedString(attachment: attachment))
normalNameString.append(NSAttributedString(string: " My Ios App", attributes: [NSAttributedString.Key.baselineOffset :6]))
self.lblText.attributedText = normalNameString

Add UILabel on UIImage to create a new UIImage [duplicate]

I have looked around and have been unsuccessful at figuring out how take text, overlay it on an image, and then combine the two into a single UIImage.
I have exhausted Google using the search terms I can think of so if anyone has a solution or at least a hint they can point to it would be greatly appreciated.
I figured it out:
func textToImage(drawText: NSString, inImage: UIImage, atPoint: CGPoint) -> UIImage{
// Setup the font specific variables
var textColor = UIColor.whiteColor()
var textFont = UIFont(name: "Helvetica Bold", size: 12)!
// Setup the image context using the passed image
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(inImage.size, false, scale)
// Setup the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
]
// Put the image into a rectangle as large as the original image
inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))
// Create a point within the space that is as bit as the image
var rect = CGRectMake(atPoint.x, atPoint.y, inImage.size.width, inImage.size.height)
// Draw the text into an image
drawText.drawInRect(rect, withAttributes: textFontAttributes)
// Create a new image out of the images we have created
var newImage = UIGraphicsGetImageFromCurrentImageContext()
// End the context now that we have the image we need
UIGraphicsEndImageContext()
//Pass the image back up to the caller
return newImage
}
To call it, you just pass in an image:
textToImage("000", inImage: UIImage(named:"thisImage.png")!, atPoint: CGPointMake(20, 20))
The following links helped me get this straight:
Swift - Drawing text with drawInRect:withAttributes:
How to write text on image in Objective-C (iOS)?
The original goal was to create a dynamic image that I could use in an AnnotaionView such as putting a price at a given location on a map and this worked out great for it.
For Swift 3:
func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 12)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
] as [String : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
For Swift 4:
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 12)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSAttributedStringKey.font: textFont,
NSAttributedStringKey.foregroundColor: textColor,
] as [NSAttributedStringKey : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
For Swift 5:
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 12)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor,
] as [NSAttributedString.Key : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
My simple solution:
func generateImageWithText(text: String) -> UIImage? {
let image = UIImage(named: "imageWithoutText")!
let imageView = UIImageView(image: image)
imageView.backgroundColor = UIColor.clear
imageView.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let label = UILabel(frame: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
label.backgroundColor = UIColor.clear
label.textAlignment = .center
label.textColor = UIColor.white
label.text = text
UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0)
imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
label.layer.render(in: UIGraphicsGetCurrentContext()!)
let imageWithText = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithText
}
You can also do a CATextLayer.
// 1
let textLayer = CATextLayer()
textLayer.frame = someView.bounds
// 2
let string = String(
repeating: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor arcu quis velit congue dictum. ",
count: 20
)
textLayer.string = string
// 3
let fontName: CFStringRef = "Noteworthy-Light"
textLayer.font = CTFontCreateWithName(fontName, fontSize, nil)
// 4
textLayer.foregroundColor = UIColor.darkGray.cgColor
textLayer.isWrapped = true
textLayer.alignmentMode = kCAAlignmentLeft
textLayer.contentsScale = UIScreen.main.scale
someView.layer.addSublayer(textLayer)
https://www.raywenderlich.com/402-calayer-tutorial-for-ios-getting-started
I have created an extension for using it everywhere :
import Foundation
import UIKit
extension UIImage {
class func createImageWithLabelOverlay(label: UILabel,imageSize: CGSize, image: UIImage) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: imageSize.width, height: imageSize.height), false, 2.0)
let currentView = UIView.init(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let currentImage = UIImageView.init(image: image)
currentImage.frame = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
currentView.addSubview(currentImage)
currentView.addSubview(label)
currentView.layer.render(in: UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
Usage :
Anywhere on your ViewController where you have the size and the label to add use it as follows -
let newImageWithOverlay = UIImage.createImageWithLabelOverlay(label: labelToAdd, imageSize: size, image: editedImage)
For swift 4:
func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedStringKey.font: UIFont(name: "Helvetica Bold", size: 12)!,NSAttributedStringKey.foregroundColor : UIColor.white , NSAttributedStringKey.paragraphStyle: paragraphStyle]
text.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
I can't see anything in your initial question suggesting that this must be done exclusively in code - so why not simply add a UILabel in interface builder, and add constraints to give it the same length and width as your image, center it vertically and horizontally (or however you need it placed), delete the label text, set the text font, size, colour, etc. as needed (including ticking Autoshrink with whatever minimum size or scale you need), and ensure it's background is transparent.
Then just connect it to an IBOutlet, and set the text in code as needed (e.g. in viewWillAppear, or by using a ViewModel approach and setting it on initialisation of your view/viewcontroller).
I have tried this basic components. Hope it will work.
func imageWithText(image : UIImage, text : String) -> UIImage {
let outerView = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width / 2, height: image.size.height / 2))
let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: outerView.frame.width, height: outerView.frame.height))
imgView.image = image
outerView.addSubview(imgView)
let lbl = UILabel(frame: CGRect(x: 5, y: 5, width: outerView.frame.width, height: 200))
lbl.font = UIFont(name: "HelveticaNeue-Bold", size: 70)
lbl.text = text
lbl.textAlignment = .left
lbl.textColor = UIColor.blue
outerView.addSubview(lbl)
let renderer = UIGraphicsImageRenderer(size: outerView.bounds.size)
let convertedImage = renderer.image { ctx in
outerView.drawHierarchy(in: outerView.bounds, afterScreenUpdates: true)
}
return convertedImage
}
It's also possible to use the QLPreviewController. Just save the imageFile to an url like the applicationsDocuments directory under the .userDomainMask and open the apple' editor. You can draw, add shapes, arrow and even your signature.
I explained the implementation in detail in the following post:
https://stackoverflow.com/a/68743098/12035498

google maps iOS SDK: custom icons to be used as markers

The Android API has a very convenient class for this, IconGenerator. Using the IconGenerator in my Android app, I can easily make a marker that:
is a simple rectangle with the color of my choosing.
resizes to hold text of any length.
is NOT an info window - I'd like the marker itself to contain the text as shown in the image below from the android version.
// 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
Is there a way to do something as simple as this in iOS using Swift?
There has been a recent release of the iOS api that allows "marker customization", but I don't see how to apply it to this use case.
// 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
Here is what I have done
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
The output is
And my marker image was
You can change your color as per your need. Also if you want something in rectange, you can just create a simple small rectangular image and use it like I did above and change the color of your need.
Or if you want a rectangle with text within it, you can just create a small UIView with some label and then convert that UIView in UIImage and can do the same thing.
//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!
}
Hope it helps!!
Here is what i have done for solving the same issue, that you are facing.
I have added below image in my image assets,
Now i added below method in my code:
-(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;
}
Now, I called this method, while assigning icon to GMSMarker, like this:
marker.icon = [self drawText:#"$33.6" inImage:[UIImage imageNamed:#"icon-marker"]];
It will generate the image icon like below:
Here, I kept the background Image size fixed, as i needed. You can still customize it to adjust it according to text size, as well as multiple lines.
UPDATE
Updated code in 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
}
You can simply add a custom view as marker in Google Map.
let marker = GMSMarker(position: coordinate)
marker.iconView = view // Your Custom view here
You can use imageView (for containing that orange color box) and label (for text) above it
I tried to rewrite Mehul Thakkar answer to Swift 3. Hope it will work for you. But it really easier to make custom view as Dari said.
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
}
Here a Swift 5 version of Eridana's Swift conversion of Mehul Thakkar's answer.
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
}
Simplest way to achieve if you have just 1 image :
marker.icon = #imageLiteral(resourceName: "fault_marker")
1) In latest XCode write marker.icon = "imageLiteral".
2) Double click the dummy image icon appeared just now.
3) select desired image.
//func to get Image view
// Url String :- Your image coming from server
//image :- Background image
func drawImageWithProfilePic(urlString:String, image: UIImage) -> UIImageView {
let imgView = UIImageView(image: image)
imgView.frame = CGRect(x: 0, y: 0, width: 90, height: 90)
let picImgView = UIImageView()
picImgView.sd_setImage(with:URL(string: urlString))
picImgView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
imgView.addSubview(picImgView)
picImgView.center.x = imgView.center.x
picImgView.center.y = imgView.center.y-10
picImgView.layer.cornerRadius = picImgView.frame.width/2
picImgView.clipsToBounds = true
imgView.setNeedsLayout()
picImgView.setNeedsLayout()
// let newImage = imageWithView(view: imgView)
// return newImage
return imgView
}
//SHOW ON MAP
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: Double(lat)!, longitude: Double(long)!)
marker.iconView = self.drawImageWithProfilePic(urlString:getProviderImage,image: UIImage.init(named: "red")!)
Simple and easiest way to change icon. just replace these 3 icon (default marker.png) to your icon (1x,2x,3x).
In Google Cluster there was a problem with marker (icon) change.

iOS Swift issue rendering label in CALayer

I am trying to render a Label in a CALayer and the background of the layer iconLayer is being placed on top of the Label.
func textToImage(drawText: NSString, inImage: UIImage, atPoint:CGPoint)->UIImage{
let textColor: UIColor = UIColor(red: 85/255, green: 150/255, blue: 230/255, alpha: 1)
let textFont: UIFont = UIFont(name: "WeatherIcons-Regular", size: 20)!
UIGraphicsBeginImageContext(inImage.size)
let layer = CALayer()
let iconLayer = CALayer()
layer.frame = CGRectMake(0, 0, inImage.size.width, inImage.size.height)
inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))
let imageSubLayer = CALayer()
imageSubLayer.contents = inImage.CGImage
let rect: CGRect = CGRectMake(atPoint.x, atPoint.y, 30, 30)
iconLayer.frame = rect
iconLayer.cornerRadius = 15.0
iconLayer.backgroundColor = UIColor.whiteColor().CGColor
layer.renderInContext(UIGraphicsGetCurrentContext()!)
iconLayer.borderColor = textColor.CGColor
iconLayer.borderWidth = 1
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
label.text = drawText as String
label.font = textFont
label.textColor = textColor
label.layer.renderInContext(UIGraphicsGetCurrentContext()!)
iconLayer.contents = label
layer.addSublayer(iconLayer)
layer.addSublayer(imageSubLayer)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
Below is what the view looks like with the background.
Below is what the view looks like with the background removed.
It seems the icon is not getting added to the layer iconLayer except it just getting added to the context.
I ended up fixing it with the following code.
func textToImage(drawText: NSString, inImage: UIImage, atPoint:CGPoint)->UIImage{
let textColor: UIColor = UIColor(red: 85/255, green: 150/255, blue: 230/255, alpha: 1)
let textFont: UIFont = UIFont(name: "WeatherIcons-Regular", size: 20)!
UIGraphicsBeginImageContext(inImage.size)
let layer = CALayer()
let iconLayer = CALayer()
layer.frame = CGRectMake(0, 0, inImage.size.width, inImage.size.height)
inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))
let imageSubLayer = CALayer()
imageSubLayer.contents = inImage.CGImage
let rect: CGRect = CGRectMake(atPoint.x, atPoint.y, 30, 30)
iconLayer.frame = rect
iconLayer.cornerRadius = 15.0
iconLayer.backgroundColor = UIColor.whiteColor().CGColor
layer.renderInContext(UIGraphicsGetCurrentContext()!)
iconLayer.borderColor = textColor.CGColor
iconLayer.borderWidth = 1
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
label.text = drawText as String
label.font = textFont
label.textColor = textColor
iconLayer.contents = label.layer
layer.addSublayer(iconLayer)
layer.addSublayer(label.layer)
layer.addSublayer(imageSubLayer)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}

Resources