I've looked around everywhere, but I can't find a way to do this. I need to create a black UIImage of a certain width and height (The width and height change, so I can't just create a black box and then load it into a UIImage). Is there some way to make a CGRect and then convert it to a UIImage? Or is there some other way to make a simple black box?
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
With Interface Builder it's pretty easy to add and configure a UIImageView. The first step is to drag the UIImageView onto your view. Then open the UIImageView properties pane and select the image asset (assuming you have some images in your project).
For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]]; My UIImage object is declared in . h file and allocated in init method, I need to set image in viewDidLoad method.
Depending on your situation, you could probably just use a UIView
with its backgroundColor
set to [UIColor blackColor]
. Also, if the image is solidly-colored, you don't need an image that's actually the dimensions you want to display it at; you can just scale a 1x1 pixel image to fill the necessary space (e.g., by setting the contentMode
of a UIImageView
to UIViewContentModeScaleToFill
).
Having said that, it may be instructive to see how to actually generate such an image:
CGSize imageSize = CGSizeMake(64, 64);
UIColor *fillColor = [UIColor blackColor];
UIGraphicsBeginImageContextWithOptions(imageSize, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
[fillColor setFill];
CGContextFillRect(context, CGRectMake(0, 0, imageSize.width, imageSize.height));
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
let imageSize = CGSize(width: 420, height: 120)
let color: UIColor = .black
UIGraphicsBeginImageContextWithOptions(imageSize, true, 0)
let context = UIGraphicsGetCurrentContext()!
color.setFill()
context.fill(CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
Like this
let image = UIGraphicsImageRenderer(size: bounds.size).image { _ in
UIColor.black.setFill()
UIRectFill(bounds)
}
As quoted in this WWDC vid
There's another function that's older; UIGraphicsBeginImageContext. But please, don't use that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With