Skip to content

Instantly share code, notes, and snippets.

@iosdevie
Created May 26, 2021 07:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iosdevie/25f42f0bca2512935cd6d72b2a19c063 to your computer and use it in GitHub Desktop.
Save iosdevie/25f42f0bca2512935cd6d72b2a19c063 to your computer and use it in GitHub Desktop.
extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
func image(byDrawingImage image: UIImage, inRect rect: CGRect) -> UIImage! {
UIGraphicsBeginImageContext(size)
draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
image.draw(in: rect)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
extension CGRect {
var center: CGPoint { return CGPoint(x: midX, y: midY) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment