Writing text to transparent UIImage - ios

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

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

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

Swift: Adding text to image does not work

I'm trying to edit an image by adding text to it, but the code I got from this post does not work: How to write text on image in Objective-C (iOS)?
My image-editing code looks like this:
func addTextToImage(image:UIImage, text:NSString, pointof: CGPoint) -> UIImage{
let font:UIFont = UIFont.boldSystemFontOfSize(12)
let dict:NSDictionary = [NSFontAttributeName : font]
UIGraphicsBeginImageContext(image.size)
image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))
let rect: CGRect = CGRectMake(pointof.x, pointof.y, image.size.width, image.size.height)
let color: UIColor = UIColor.whiteColor()
text.drawInRect(CGRectIntegral(rect), withAttributes:dict)
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
And then I use the textViewDidChange method to add the text to the image, but it does not work:
func textViewDidChange(textView: UITextView){
backgroundImage.image = addTextToImage(imageToView, text: textViewer.text, pointof: CGPointMake(0, 0))
}
Any suggestions on what I'm doing wrong would be appreciated.
func addTextToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage
{
let textColor = UIColor.blue
let textFont = UIFont(name: "ChalkboardSE-Regular", size: 26)!
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!
}

Create UIImage with solid color in Swift

I want to programmatically create an UIImage filled by a solid color. Anyone have an idea of how to do this in Swift?
Another nice solution,
Swift 3.0
public extension UIImage {
convenience init?(color: 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()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
Swift 2.2 compatible, is to create another constructor in UIImage, in this way:
public extension UIImage {
public convenience init?(color: 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()
guard let cgImage = image?.CGImage else { return nil }
self.init(CGImage: cgImage)
}
}
In this way you can create the custom colored-image in this way:
let redImage = UIImage(color: .redColor())
Or, optionally, create the image with a custom size:
let redImage200x200 = UIImage(color: .redColor(), size: CGSize(width: 200, height: 200))
Swift 4 version:
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))
}
}
}
Usage:
let image0 = UIColor.orange.image(CGSize(width: 128, height: 128))
let image1 = UIColor.yellow.image()
Here's another option. I believe you wanted an exact UIImage object.
func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
Stick this in your Swift code and call it
Swift 3.1:
func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
A cleaner approach would be to encapsulate the logic inside an UIImage extension:
import UIKit
extension UIImage {
class func imageWithColor(color: UIColor) -> UIImage {
let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
Now the consumer can call, UIImage.imageWithColor(UIColor.blackColor()) to create an image with black background.
A minor tweak to #neoneye's excellent answer, allowing the calling code not to need to create the CGSize, and altered the name to not collide with numerous others:
Swift 4
extension UIColor {
func imageWithColor(width: Int, height: Int) -> UIImage {
let size = CGSize(width: width, height: height)
return UIGraphicsImageRenderer(size: size).image { rendererContext in
self.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
}
}
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.backgroundColor = UIColor.redColor()
}
}
Similar method if you want draw the image yourself vs. connecting one via IBOutlet.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var frame = CGRectMake(100,100,100,100)
var imageView2 = UIImageView(frame: frame)
imageView2.backgroundColor = UIColor.redColor()
self.view.addSubview(imageView2)
}
}
Third method borrowing from anthonyliao. A little more complicated:
class ViewController: UIViewController {
func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(CGRectMake(0, 0, 100, 100))
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
override func viewDidLoad() {
super.viewDidLoad()
var imageView = UIImageView(frame: CGRectMake(100,100,100,100))
let screenImage = getImageWithColor(UIColor.redColor(), size: CGSize(width: 100, height: 100))
imageView.image = screenImage
self.view.addSubview(imageView)
}
}
You can use the new iOS 10 UIGraphicsImageRenderer API.
Here is an extension on UIColor in Swift 3.1
extension UIColor {
func getImage(size: CGSize) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: size)
return renderer.image(actions: { rendererContext in
self.setFill()
rendererContext.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
})
}}
A nice way is to have a computed property like this:
extension UIColor {
var imageRepresentation : UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(self.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
Usage:
let redImage = UIColor.red.imageRepresentation
Swift 3 version of #anthonyliao Accepted answer:
class func getImageWithColor(color: UIColor, size: CGSize) -> UIImage
{
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: size.width, height: size.height))
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
Rect with rounded corners
extension UIImage {
convenience init?(color: UIColor) {
let rect = CGRect(x: 0, y: 0, width: 10, height: 2)
UIGraphicsBeginImageContextWithOptions(CGSize(width: 10, height: 2), false, 0)
let bezierPath = UIBezierPath(roundedRect: rect, cornerRadius: 8)
color.setFill()
bezierPath.fill()
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
guard let cgImage = image.cgImage else {
return nil
}
self.init(cgImage: cgImage)
}
}
Swift 5, Xcode 12.4 - UIImageView's solution
If you have to deal with UIImageViews like in my case, you could opt for a more compact solution like: exampleImageView.fill() or exampleImageView.fill(with: .black).
Extension's code:
extension UIImageView {
func fill(with color: UIColor = .lightGray) {
let size = self.bounds.size
let image = UIGraphicsImageRenderer(size: size).image { rendererContext in
color.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
self.image = image
}
}
we can use UIGraphicsImageRenderer to create the UIImage or use traditional CGContext approach, below is convenience init function which creates UIImage with given color
extension UIImage {
/// create UIImage with color and given size
convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1), alpha: CGFloat = 1, scale: CGFloat = 0) {
if #available(tvOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(size: size)
let image = renderer.image { (ctx) in
let size = renderer.format.bounds.size
ctx.fill(CGRect(origin: .zero, size: size))
ctx.cgContext.setFillColor(color.cgColor)
}
guard let cgImage = image.cgImage else { return nil }
self.init(cgImage: cgImage)
} else {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, scale)
let context = UIGraphicsGetCurrentContext()!
let fillColor = color.withAlphaComponent(alpha)
context.setFillColor(fillColor.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
}
Swift 5
/ Get not optional UIImage
public static func withColor(_ color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let image = UIGraphicsImageRenderer(size: size, format: format).image { rendererContext in
color.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
return image
}
Don't forget to use format.scale = 1 if it needed
If your application support iOS 10 or above, we should use UIGraphicsImageRenderer since it is faster.
Here are some static methods / init methods (optional UIImage) in UIImage's extension:
import UIKit
extension UIImage {
static func from(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
let format = UIGraphicsImageRendererFormat()
format.scale = 1
return UIGraphicsImageRenderer(size: size, format: format).image { context in
color.setFill()
context.fill(CGRect(origin: .zero, size: size))
}
}
static func from(color: UIColor, size: CGFloat = 1) -> UIImage {
return from(color: color, size: CGSize(width: size, height: size))
}
static func from(color: UIColor) -> UIImage {
return from(color: color, size: 1)
}
convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let image = UIGraphicsImageRenderer(size: size, format: format).image { context in
color.setFill()
context.fill(CGRect(origin: .zero, size: size))
}
guard let cgImage = image.cgImage else { return nil }
self.init(cgImage: cgImage)
}
convenience init?(color: UIColor, size: CGFloat = 1) {
self.init(color: color, size: CGSize(width: size, height: size))
}
convenience init?(color: UIColor) {
self.init(color: color, size: 1)
}
}
struct Example {
func createAnImageWithColorRed() {
UIImage(color: .red, size: CGSize(width: 10, height: 10))
UIImage(color: .red, size: 10)
UIImage(color: .red)
UIImage.from(color: .red, size: CGSize(width: 10, height: 10))
UIImage.from(color: .red, size: 10)
UIImage.from(color: .red)
}
}
Preview:

Resources