Skip to content

Instantly share code, notes, and snippets.

@usagimaru
Created March 10, 2018 17:29
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 usagimaru/3a38d9f90b2daa007a1a79d2b08f0e43 to your computer and use it in GitHub Desktop.
Save usagimaru/3a38d9f90b2daa007a1a79d2b08f0e43 to your computer and use it in GitHub Desktop.
Paint UIImage with any UIColor
import UIKit
extension UIImage {
func paintedImage(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let bounds = CGRectMake(0, 0, size.width, size.height)
let context = UIGraphicsGetCurrentContext()
drawInRect(bounds)
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextSetBlendMode(context, .SourceAtop) // SourceAtop にすることで画像の透過を考慮してくれる
CGContextFillRect(context, bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
/*
let image: UIImage = …
let color: UIColor = …
let paintedImage = image.paintedImage(color)
*/
// https://qiita.com/usagimaru/items/5400fa74ab538ce3804c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment