Skip to content

Instantly share code, notes, and snippets.

@Arcovv
Last active August 24, 2017 10:12
Show Gist options
  • Save Arcovv/867f667f5a14eb65deaacf9db2120481 to your computer and use it in GitHub Desktop.
Save Arcovv/867f667f5a14eb65deaacf9db2120481 to your computer and use it in GitHub Desktop.
Some of the small methods to handle UIImage
import UIKit
extension UIImage {
func fill(with color: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext(), let cgImage = cgImage else { return nil }
let rect = CGRect(origin: .zero, size: size)
let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: rect.size.height)
context.concatenate(flipVertical)
context.setFillColor(color.cgColor)
context.setBlendMode(.normal)
context.draw(cgImage, in: rect)
context.setBlendMode(.sourceIn)
context.addRect(rect)
context.drawPath(using: .fill)
let image = UIGraphicsGetImageFromCurrentImageContext() ; defer { UIGraphicsEndImageContext() }
return image?.withRenderingMode(.alwaysOriginal)
}
func resize(_ size: CGSize) -> UIImage? {
let rect = CGRect(origin: .zero, size: size)
return redraw(in: rect)
}
func redraw(in rect: CGRect) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext(), let cgImage = cgImage else { return nil }
let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: rect.size.height)
context.concatenate(flipVertical)
context.draw(cgImage, in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext() ; defer { UIGraphicsEndImageContext() }
return image
}
func circled(forRadius radius: CGFloat) -> UIImage? {
let rediusSize = CGSize(width: radius, height: radius)
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext(), let cgImage = cgImage else { return nil }
let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: rect.size.height)
context.concatenate(flipVertical)
let bezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: [.allCorners], cornerRadii: rediusSize)
context.addPath(bezierPath.cgPath)
context.clip()
context.drawPath(using: .fillStroke)
context.draw(cgImage, in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext() ; defer { UIGraphicsEndImageContext() }
return image
}
static func get(with color: UIColor) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
context.setFillColor(color.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext() ; defer { UIGraphicsEndImageContext() }
return image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment