Skip to content

Instantly share code, notes, and snippets.

@ppamorim
Created November 5, 2015 16:30
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ppamorim/cc79170422236d027b2b to your computer and use it in GitHub Desktop.
Save ppamorim/cc79170422236d027b2b to your computer and use it in GitHub Desktop.
Add padding/margin at a image!
import UIKit
extension UIImage {
func imageWithInsets(insetDimen: CGFloat) -> UIImage {
return imageWithInset(UIEdgeInsets(top: insetDimen, left: insetDimen, bottom: insetDimen, right: insetDimen))
}
func imageWithInset(insets: UIEdgeInsets) -> UIImage {
UIGraphicsBeginImageContextWithOptions(
CGSizeMake(self.size.width + insets.left + insets.right,
self.size.height + insets.top + insets.bottom), false, self.scale)
let origin = CGPoint(x: insets.left, y: insets.top)
self.drawAtPoint(origin)
let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithInsets
}
}
@volkov-maxim
Copy link

@dterekhov you forgot about renderingMode and the correct scale. Here is a fully operational solution:

extension UIImage {
    
    func with(_ insets: UIEdgeInsets) -> UIImage {
        let targetWidth = size.width + insets.left + insets.right
        let targetHeight = size.height + insets.top + insets.bottom
        let targetSize = CGSize(width: targetWidth, height: targetHeight)
        let targetOrigin = CGPoint(x: insets.left, y: insets.top)
        let format = UIGraphicsImageRendererFormat()
        format.scale = scale
        let renderer = UIGraphicsImageRenderer(size: targetSize, format: format)
        return renderer.image { _ in
            draw(in: CGRect(origin: targetOrigin, size: size))
        }.withRenderingMode(renderingMode)
    }
    
}

Thank you! It very useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment