Skip to content

Instantly share code, notes, and snippets.

@inekipelov
Forked from clayellis/UIImage+Extras
Created February 1, 2026 20:29
Show Gist options
  • Select an option

  • Save inekipelov/8a869c24287a515453bd73760f4ef8f5 to your computer and use it in GitHub Desktop.

Select an option

Save inekipelov/8a869c24287a515453bd73760f4ef8f5 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