Skip to content

Commit

Permalink
added pixel-to-color conversion methods
Browse files Browse the repository at this point in the history
  • Loading branch information
juliand665 committed Feb 19, 2018
1 parent 4fc4d4d commit 081cc3d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Bitmap/AppKit/Helpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
15 changes: 15 additions & 0 deletions Bitmap/UIKit/Helpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

0 comments on commit 081cc3d

Please sign in to comment.