Skip to content

Instantly share code, notes, and snippets.

@clayellis
Created March 23, 2017 17:13
Show Gist options
  • Save clayellis/3c3bfdee9cac8e9b12ecaefb103d916b to your computer and use it in GitHub Desktop.
Save clayellis/3c3bfdee9cac8e9b12ecaefb103d916b to your computer and use it in GitHub Desktop.
//
// UIImage+Extras.swift
// Clay Ellis
// https://gist.github.com/clayellis/3c3bfdee9cac8e9b12ecaefb103d916b
//
import UIKit
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)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
func with(alpha value: CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: .zero, blendMode: .normal, alpha: value)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment