This isn't what you probably thought it was to begin with. I know how to use UIImage's, but I now need to know how to create a "blank" UIImage using:
CGRect screenRect = [self.view bounds];
Well, those dimensions. Anyway, I want to know how I can create a UIImage with those dimensions colored all white. No actual images here.
Is this even possible? I am sure it is, but maybe I am wrong.
This needs to be a "white" image. Not a blank one. :)
To create a new UIImage programmatically in Swift, we simply need to create a new instance of UIImage providing it with the name of the image we have added to a Resources folder. Once we have an instance of UIImage created, we can add it to a UIImageView.
Drag and drop image onto Xcode's assets catalog. Or, click on a plus button at the very bottom of the Assets navigator view and then select “New Image Set”. After that, drag and drop an image into the newly create Image Set, placing it at appropriate 1x, 2x or 3x slot.
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). You can also configure how the underlying image is scaled to fit inside the UIImageView.
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
You need to use CoreGraphics
, as follows.
CGSize size = CGSizeMake(desiredWidth, desiredHeight); UIGraphicsBeginImageContextWithOptions(size, YES, 0); [[UIColor whiteColor] setFill]; UIRectFill(CGRectMake(0, 0, size.width, size.height)); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
The code creates a new CoreGraphics
image context with the options passed as parameters; size, opaqueness, and scale. By passing 0
for scale, iOS automatically chooses the appropriate value for the current device.
Then, the context fill colour is set to [UIColor whiteColor]
. Immediately, the canvas is then actually filled with that color, by using UIRectFill()
and passing a rectangle which fills the canvas.
A UIImage
is then created of the current context, and the context is closed. Therefore, the image variable contains a UIImage
of the desired size, filled white.
Swift version:
extension UIImage { static func emptyImage(with size: CGSize) -> UIImage? { UIGraphicsBeginImageContext(size) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
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