UIImage With Color & Centered Text - ios

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!)
}

Related

Position CGRect in the center for text output

So I have the following code:
let number = cluster.memberAnnotations.count
displayPriority = .defaultHigh
image = textToImage(
drawText: "\(number)",
inImage: UIImage(named: "map-pin-full-cluster-1")!
.withTintColor(.blue, renderingMode: . alwaysTemplate)
.resizeWith(
newSize: CGSize(width: 35, height: 35)), atPoint: CGPointMake(14.5, 3.5)
)
Which outputs the following look on the map:
Here is a function that I am using to assist me:
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!
}
Problem:
When the number ends up going into double digit, it isn't contained within the circle, how can I format my code so that I can center a number based on a CRect or other call?
:
Got it working thanks to #Larme's guidance:
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.paragraphStyle: paragraph,
] as [NSAttributedString.Key : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
Define a NSMutableParagraphStyle() and set the paragraphStyle to it's attribute.

Writing text to transparent UIImage

I want to write a text string on a fully transparent image (alpha 0 everywhere) but it doesn't work. The background of the image turns to be white if alpha of background image is 0. Here are the approaches I tried:
extension UIColor {
func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { rendererContext in
self.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
}
}
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.blue
let textFont = UIFont(name: "Helvetica Bold", size: 40)!
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!
}
And then:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let inImage = UIColor.black.withAlphaComponent(0).image(CGSize(width: 800, height: 800))
//Even tried inImage = UIImage(named: "Transparent") where Transparent.png is fully transparent image! //
let image = textToImage(drawText: "Test String", inImage: inImage, atPoint: CGPoint(x: 0, y: 0))
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
No matter what I do, the background is white.
Try converting to png
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let inImage = UIColor.black.withAlphaComponent(0).image(CGSize(width: 800, height: 800))
//Even tried inImage = UIImage(named: "Transparent") where Transparent.png is fully transparent image! //
let image = textToImage(drawText: "Test String", inImage: inImage, atPoint: CGPoint(x: 0, y: 0))
self.image.image = image
if let pngdata = image.pngData() {
if let newImage = UIImage(data: pngdata) {
UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil)
}
}
}
I've tested Your code in playgroung, and it works as it should
So The reason is Apple Gallery representations of alpha channels. Looks like it's not supported

iOS swift: Image from label in TabBarItem

I'm trying to create a gray circle with name initials indie of it. And use it as tabBarItem image.
This is the function that I use to create the circle, and it almost works, as you can see in the image below, but it's a square not a circle:
static func createAvatarWithInitials(name: String, surname: String, size: CGFloat) -> UIImage {
let initialsLabel = UILabel()
initialsLabel.frame.size = CGSize(width: size, height: size)
initialsLabel.textColor = UIColor.white
initialsLabel.text = "\(name.characters.first!)\(surname.characters.first!)"
initialsLabel.textAlignment = .center
initialsLabel.backgroundColor = UIColor(red: 74.0/255, green: 77.0/255, blue: 78.0/255, alpha: 1.0)
initialsLabel.layer.cornerRadius = size/2
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(initialsLabel.frame.size, false, scale)
initialsLabel.layer.render(in: UIGraphicsGetCurrentContext()!)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
image.withRenderingMode(.alwaysOriginal)
return image
}
and this is how I call it inside the viewDidLoad of the tabBarController:
if index == positionForProfileItem {
tabBarItem.image = UIImage.createAvatarWithInitials(name: "John", surname: "Doe", size: CGFloat(20))
}
but I got an empty squared rectangle in the tab bar.. And I can't figure it out the reason, any help?
The UIImage withRenderingMode method returns a new image. It does not modify the sender.
Change the last two lines to just one:
return image.withRenderingMode(.alwaysOriginal)
But that is not what you wish to do. Since you want a template image of a circle with the text in the middle, you need to do the following:
static func createAvatarWithInitials(name: String, surname: String, size: CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0)
let ctx = UIGraphicsGetCurrentContext()!
// Draw an opague circle
UIColor.white.setFill()
let circle = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: size, height: size))
circle.fill()
// Setup text
let font = UIFont.systemFont(ofSize: 17)
let text = "\(name.characters.first!)\(surname.characters.first!)"
let textSize = (text as NSString).size(withAttributes: [ .font: font ])
// Erase text
ctx.setBlendMode(.clear)
let textRect = CGRect(x: (size - textSize.width) / 2, y: (size - textSize.height) / 2, width: textSize.width, height: textSize.height)
(text as NSString).draw(in: textRect, withAttributes: [ .font: font ])
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
You have to add clipsToBounds=YES on your label for cornerRadius to have efect on your screen shoot, and also try to increase a little bit the size of your image from 20 to 30.

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

Convert Apple Emoji (String) to UIImage

I need all Apple Emojis. I can get all the emojis and put them into a String by copying them from the site getemoji but in my app i need the emojis in the right order as images.
Is there a nice way to convert the emojis I copy into a String to a UIImage?
Or a better solution to get all the Apple emojis in the right order?
Updated for Swift 4.1
Add this extension to your project
import UIKit
extension String {
func image() -> UIImage? {
let size = CGSize(width: 40, height: 40)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.white.set()
let rect = CGRect(origin: .zero, size: size)
UIRectFill(CGRect(origin: .zero, size: size))
(self as AnyObject).draw(in: rect, withAttributes: [.font: UIFont.systemFont(ofSize: 40)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
The code above draws the current String to an Image Context with a white background color and finally transform it into a UIImage.
Now you can write
Example
Given a list of ranges indicating the unicode values of the emoji symbols
let ranges = [0x1F601...0x1F64F, 0x2702...0x27B0]
you can transform it into a list of images
let images = ranges
.flatMap { $0 }
.compactMap { Unicode.Scalar($0) }
.map(Character.init)
.compactMap { String($0).image() }
Result:
I cannot guarantee the list of ranges is complete, you'll need to search for it by yourself 😉
Here's an updated answer with the following changes:
Centered: Used draw(at:withAttributes:) instead of draw(in:withAttributes:) for centering the text within the resulting UIImage
Correct Size: Used size(withAttributes:) for having a resulting UIImage of size that correlates to the actual size of the font.
Comments: Added comments for better understanding
Swift 5
import UIKit
extension String {
func textToImage() -> UIImage? {
let nsString = (self as NSString)
let font = UIFont.systemFont(ofSize: 1024) // you can change your font size here
let stringAttributes = [NSAttributedString.Key.font: font]
let imageSize = nsString.size(withAttributes: stringAttributes)
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) // begin image context
UIColor.clear.set() // clear background
UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) // set rect size
nsString.draw(at: CGPoint.zero, withAttributes: stringAttributes) // draw text within rect
let image = UIGraphicsGetImageFromCurrentImageContext() // create image from context
UIGraphicsEndImageContext() // end image context
return image ?? UIImage()
}
}
Swift 3.2
import UIKit
extension String {
func textToImage() -> UIImage? {
let nsString = (self as NSString)
let font = UIFont.systemFont(ofSize: 1024) // you can change your font size here
let stringAttributes = [NSFontAttributeName: font]
let imageSize = nsString.size(attributes: stringAttributes)
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) // begin image context
UIColor.clear.set() // clear background
UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) // set rect size
nsString.draw(at: CGPoint.zero, withAttributes: stringAttributes) // draw text within rect
let image = UIGraphicsGetImageFromCurrentImageContext() // create image from context
UIGraphicsEndImageContext() // end image context
return image ?? UIImage()
}
}
Same thing for Swift 4:
extension String {
func emojiToImage() -> UIImage? {
let size = CGSize(width: 30, height: 35)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.white.set()
let rect = CGRect(origin: CGPoint(), size: size)
UIRectFill(rect)
(self as NSString).draw(in: rect, withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 30)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Updated #Luca Angeletti answer for Swift 3.0.1
extension String {
func image() -> UIImage? {
let size = CGSize(width: 30, height: 35)
UIGraphicsBeginImageContextWithOptions(size, false, 0);
UIColor.white.set()
let rect = CGRect(origin: CGPoint(), size: size)
UIRectFill(CGRect(origin: CGPoint(), size: size))
(self as NSString).draw(in: rect, withAttributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 30)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Swift 4.2
I really liked #Luca Angeletti solution. I hade the same question as #jonauz about transparent background. So with this small modification you get the same thing but with clear background color.
I didn't have the rep to answer in a comment.
import UIKit
extension String {
func emojiToImage() -> UIImage? {
let size = CGSize(width: 30, height: 35)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.clear.set()
let rect = CGRect(origin: CGPoint(), size: size)
UIRectFill(CGRect(origin: CGPoint(), size: size))
(self as NSString).draw(in: rect, withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 30)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Swift 5: ( with optional fontSize, imageSize and bgColor)
use it like this:
let image = "🤣".image()
let imageLarge = "🤣".image(fontSize:100)
let imageBlack = "🤣".image(fontSize:100, bgColor:.black)
let imageLong = "🤣".image(fontSize:100, imageSize:CGSize(width:500,height:100))
import UIKit
extension String
{
func image(fontSize:CGFloat = 40, bgColor:UIColor = UIColor.clear, imageSize:CGSize? = nil) -> UIImage?
{
let font = UIFont.systemFont(ofSize: fontSize)
let attributes = [NSAttributedString.Key.font: font]
let imageSize = imageSize ?? self.size(withAttributes: attributes)
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
bgColor.set()
let rect = CGRect(origin: .zero, size: imageSize)
UIRectFill(rect)
self.draw(in: rect, withAttributes: [.font: font])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Updated version of #Luca Angeletti's answer using UIGraphicsImageRenderer:
extension String {
func image() -> UIImage? {
let size = CGSize(width: 100, height: 100)
let rect = CGRect(origin: CGPoint(), size: size)
return UIGraphicsImageRenderer(size: size).image { (context) in
(self as NSString).draw(in: rect, withAttributes: [.font : UIFont.systemFont(ofSize: 100)])
}
}
}
This variation is based on #Luca's accepted answer, but allows you to optionally customize the point size of the font, should result in a centered image, and doesn't make the background color white.
extension String {
func image(pointSize: CGFloat = UIFont.systemFontSize) -> UIImage? {
let nsString = self as NSString
let font = UIFont.systemFont(ofSize: pointSize)
let size = nsString.size(withAttributes: [.font: font])
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let rect = CGRect(origin: .zero, size: size)
nsString.draw(in: rect, withAttributes: [.font: font])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}

Resources