Edited at

【Swift】UIImageの色を変える(塗りつぶす)

More than 1 year has passed since last update.

こんなシンプルな内容

2018/01/18 更新


Swift4


UIImageExtension.swift

extension UIImage {

func tint(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
let drawRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIRectFill(drawRect)
draw(in: drawRect, blendMode: .destinationIn, alpha: 1)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage
}
}


Swift2


UIImageExtension.swift

extension UIImage {

func tint(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
let drawRect = CGRectMake(0, 0, size.width, size.height)
UIRectFill(drawRect)
drawInRect(drawRect, blendMode: kCGBlendModeDestinationIn, alpha: 1)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage
}
}

同じ画像の色違いを表示したい時には使える関数だと思います。