Recently I was updating an iOS app and found myself needing to set a background image on a UIButton. Easy enough, except that each image needed to use an existing image asset used elsewhere in the app, which needed to be centered on top of a gradient background with a border. While I could have easily made another couple of images that had the background/border treatment baked into the image, I chose to “make” new versions of the images by placing them inside of a UIView, which had the necessary border and background treatment, and converting the UIView to a UIImage that I could use as the background for the UIButton.
Now converting a UIView to a UIImage is nothing new, and there are lots of folks and forums out there that have posted solutions. However I still think it’s nice to keep the following snippet of code on hand, be it as an instance or class method, or even by extending UIImage with a category.
- (UIImage *) imageFromUIView:(UIView*)view
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
One thing that has tripped me up in the past is the arguments in the UIGraphicsBeginImageContextWithOptions function used in the first line of this method. As specified in the UIKit Function Reference, the 3 arguments are CGSize size, BOOL opaque, and CGFloat scale. Most specifically, it’s worth noting that by setting the scale argument to 0.0, the scale factor is set to the scale factor of the device’s main screen, which is helpful to do when dealing with retina- and non-retina displays.
Again, nothing new or earth shattering, but a good but of code to keep at the ready.
Until next time, happy coding!