How to create a colored 1x1 UIImage on the iPhone dynamically?
You can use CGContextSetFillColorWithColor
and CGContextFillRect
for this:
Swift
extension UIImage {
class func image(with color: UIColor) -> UIImage {
let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Swift3
extension UIImage {
class func image(with color: UIColor) -> UIImage {
let rect = CGRect(origin: CGPoint(x: 0, y:0), size: CGSize(width: 1, height: 1))
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
Objective-C
+ (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Trying to create a colored circle UIImage, but it always ends up square. Why?
The newer way is to use UIGraphicsImageRenderer which gives you the correct point scale automatically. Also a path can fill itself so there is no need for a clipping mask:
func circleFromColor(_ color: UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) -> UIImage? {
UIGraphicsImageRenderer(size: size).image { context in
color.setFill()
UIBezierPath(ovalIn: .init(origin: .zero, size: size)).fill()
}
}
Here is how you do it the old way:
func circleFromColor(_ color: UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) -> UIImage? {
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
context.setFillColor(color.cgColor)
let radius: CGFloat = 8.0 * UIScreen.main.scale
let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius))
maskPath.addClip()
maskPath.fill()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
How to create a UIImage programmatically with contents
This will help you
UIImage *image1 = [UIImage imageNamed:@"image1.png"];
UIImage *image2 = [UIImage imageNamed:@"image2.png"];
CGSize newSize = CGSizeMake(width, height);
UIGraphicsBeginImageContext( newSize );
[image1 drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
[image2 drawInRect:CGRectMake(0,0,newSize.width,newSize.height) blendMode:kCGBlendModeNormal alpha:0.8];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
How to create UIImage object by url(swfit?)
A method that get image from url
func getImageWithURL(urlString:String,completion: @escaping (_ image:UIImage?) -> Void) {
guard let url = URL(string: urlString) else {
print("invalid url")
completion(nil)
return
}
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url) {
DispatchQueue.main.async {
let image = UIImage(data: data)
completion(image)
}
} else {
print("Error: Url not conataining Image")
completion(nil)
}
}
}
and how you can call it
getImageWithURL(urlString: "https://picsum.photos/200") { image in
if let image = image {
print("there is an image")
let pngData = image.pngData()
let jpegData = image.jpegData(compressionQuality: 1.0)
}
}
Create UIImage with solid color 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))
Creating UIImage programmatically from UIView
+ (UIImage *)imageWithColor:(UIColor *)color andRect:(CGRect)rect {
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Related Topics
Formatting a Uitextfield for Credit Card Input Like (Xxxx Xxxx Xxxx Xxxx)
How to Add a 'Done' Button to Numpad Keyboard in iOS
iOS 8 Swift - Tableview with Embedded Collectionview
Adding Navigation Bar Programmatically iOS
Auto-Renewable Subscription in iOS7
How to Programmatically Fake a Touch Event to a Uibutton
How to Add Badges on Uibarbutton Item
How to Distribute My App for Any Device Without Udid
What Does "@Private" Mean in Objective-C
How to Simultaneously Satisfy Constraints - No Constraints in Place
"Untrusted App Developer" Message When Installing Enterprise iOS Application
Uibutton Image for Normal State in Collectionview Cell Repeats Itself Every Four Cells
How to Create Custom Mkannotationview and Custom Annotation Title and Subtitle
Creating Delegates on the Spot with Blocks
Rotation Methods Deprecated, Equivalent of 'Didrotatefrominterfaceorientation'