Created
November 5, 2015 16:30
-
-
Save ppamorim/cc79170422236d027b2b to your computer and use it in GitHub Desktop.
Add padding/margin at a image!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
@dterekhov you forgot about
renderingMode
and the correctscale
. 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
@dterekhov you forgot about
renderingMode
and the correctscale
. Here is a fully operational solution: