LoginSignup
5
2

More than 5 years have passed since last update.

指定の色で塗り替えた UIImage を作る

Posted at

UIImageView には Tint Color の仕組みがあるので、Template Image にしておけばその画像は Tint Color で塗りつぶした見た目になる。が、UIImageView を使わずに描画したい場合がでてきたので以下のエクステンションで対応した。

import UIKit

extension UIImage {

    func coloredImage(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
    }

}

なお、macOS の Cocoa には自由に設定できる Tint Color の仕組みが見つからなかったため、NSImage でも同様のエクステンションを実装した。
NSImage に Tint Color を適用する機能を拡張する

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2