Created
March 10, 2018 17:29
-
-
Save usagimaru/3a38d9f90b2daa007a1a79d2b08f0e43 to your computer and use it in GitHub Desktop.
Paint UIImage with any UIColor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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