diff --git a/Bitmap/AppKit/Helpers.swift b/Bitmap/AppKit/Helpers.swift index 206efbf..7478660 100644 --- a/Bitmap/AppKit/Helpers.swift +++ b/Bitmap/AppKit/Helpers.swift @@ -18,4 +18,19 @@ extension Pixel { public init(_ cgColor: CGColor) { self.init(NSColor(cgColor: cgColor)!) } + + /** + Creates a new `NSColor` from the pixel, taking alpha premultiplication into account. + + There is some loss of information, e.g. a fully transparent red pixel loses information about its color due to alpha premultiplication. For fully transparent pixels, this method returns a fully transparent black color (`r=g=b=a=0`). + */ + var nsColor: NSColor { + guard self.alpha > 0 else { return #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0) } + let alpha = CGFloat(self.alpha) // stupid premultiplication + let color = NSColor(red: CGFloat(red) / alpha, + green: CGFloat(green) / alpha, + blue: CGFloat(blue) / alpha, + alpha: alpha / 255) + return color + } } diff --git a/Bitmap/UIKit/Helpers.swift b/Bitmap/UIKit/Helpers.swift index 68590eb..535b49a 100644 --- a/Bitmap/UIKit/Helpers.swift +++ b/Bitmap/UIKit/Helpers.swift @@ -17,4 +17,19 @@ extension Pixel { public init(_ cgColor: CGColor) { self.init(UIColor(cgColor: cgColor)) } + + /** + Creates a new `UIColor` from the pixel, taking alpha premultiplication into account. + + There is some loss of information, e.g. a fully transparent red pixel loses information about its color due to alpha premultiplication. For fully transparent pixels, this method returns a fully transparent black color (`r=g=b=a=0`). + */ + var uiColor: UIColor { + guard self.alpha > 0 else { return #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0) } + let alpha = CGFloat(self.alpha) // stupid premultiplication + let color = UIColor(red: CGFloat(red) / alpha, + green: CGFloat(green) / alpha, + blue: CGFloat(blue) / alpha, + alpha: alpha / 255) + return color + } }