Add transparent space around a UIImage
In Swift you can write an extension to UIImage that draws image with insets around it.
Swift 3:
import UIKitextension UIImage { func imageWithInsets(insets: UIEdgeInsets) -> UIImage? { UIGraphicsBeginImageContextWithOptions( CGSize(width: self.size.width + insets.left + insets.right, height: self.size.height + insets.top + insets.bottom), false, self.scale) let _ = UIGraphicsGetCurrentContext() let origin = CGPoint(x: insets.left, y: insets.top) self.draw(at: origin) let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageWithInsets }}
OLD ANSWER:
import UIKitextension UIImage { func imageWithInsets(insets: UIEdgeInsets) -> UIImage { UIGraphicsBeginImageContextWithOptions( CGSizeMake(self.size.width + insets.left + insets.right, self.size.height + insets.top + insets.bottom), false, self.scale) let context = UIGraphicsGetCurrentContext() let origin = CGPoint(x: insets.left, y: insets.top) self.drawAtPoint(origin) let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageWithInsets }}
This is the solution in Swift 4 inspired by DrummerB answer:
import UIKitextension UIImage { func addImagePadding(x: CGFloat, y: CGFloat) -> UIImage? { let width: CGFloat = size.width + x let height: CGFloat = size.height + y UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 0) let origin: CGPoint = CGPoint(x: (width - size.width) / 2, y: (height - size.height) / 2) draw(at: origin) let imageWithPadding = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageWithPadding }}
How to apply:
let image = UIImage(named: "your-image")!let imageView = UIImageView(image: image.addImagePadding(x: 50, y: 50))imageView.backgroundColor = UIColor.grayview.addSubview(imageView)
Features:
- Simply pass padding values via parameters
- Colored padding (by setting the UIGraphicsBeginImageContextWithOptions opaque parameter to false)
You create a new image context that is 1000x1000, draw your old image in the middle, then get the new UIImage
from the context.
// Setup a new context with the correct sizeCGFloat width = 1000;CGFloat height = 1000;UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0); CGContextRef context = UIGraphicsGetCurrentContext(); UIGraphicsPushContext(context); // Now we can draw anything we want into this new context.CGPoint origin = CGPointMake((width - oldImage.size.width) / 2.0f, (height - oldImage.size.height) / 2.0f);[oldImage drawAtPoint:origin];// Clean up and get the new image.UIGraphicsPopContext(); UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();