Skip to content

Commit 081cc3d

Browse files
committed
added pixel-to-color conversion methods
1 parent 4fc4d4d commit 081cc3d

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

Bitmap/AppKit/Helpers.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,19 @@ extension Pixel {
1818
public init(_ cgColor: CGColor) {
1919
self.init(NSColor(cgColor: cgColor)!)
2020
}
21+
22+
/**
23+
Creates a new `NSColor` from the pixel, taking alpha premultiplication into account.
24+
25+
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`).
26+
*/
27+
var nsColor: NSColor {
28+
guard self.alpha > 0 else { return #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0) }
29+
let alpha = CGFloat(self.alpha) // stupid premultiplication
30+
let color = NSColor(red: CGFloat(red) / alpha,
31+
green: CGFloat(green) / alpha,
32+
blue: CGFloat(blue) / alpha,
33+
alpha: alpha / 255)
34+
return color
35+
}
2136
}

Bitmap/UIKit/Helpers.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,19 @@ extension Pixel {
1717
public init(_ cgColor: CGColor) {
1818
self.init(UIColor(cgColor: cgColor))
1919
}
20+
21+
/**
22+
Creates a new `UIColor` from the pixel, taking alpha premultiplication into account.
23+
24+
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`).
25+
*/
26+
var uiColor: UIColor {
27+
guard self.alpha > 0 else { return #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0) }
28+
let alpha = CGFloat(self.alpha) // stupid premultiplication
29+
let color = UIColor(red: CGFloat(red) / alpha,
30+
green: CGFloat(green) / alpha,
31+
blue: CGFloat(blue) / alpha,
32+
alpha: alpha / 255)
33+
return color
34+
}
2035
}

0 commit comments

Comments
 (0)