Skip to content

Instantly share code, notes, and snippets.

@cobysy
Created June 27, 2014 12:13
Show Gist options
  • Save cobysy/adc38ad1106f98fff2a8 to your computer and use it in GitHub Desktop.
Save cobysy/adc38ad1106f98fff2a8 to your computer and use it in GitHub Desktop.
Calculate color similarity/distance in RGBA color space
@implementation NSColor (DDExtensions)
- (float)distanceTo:(NSColor*)color
{
// Calculate color similarity/distance in RGBA color space
// http://stackoverflow.com/questions/4754506/color-similarity-distance-in-rgba-color-space
// max((r₁-r₂)², (r₁-r₂ - a₁+a₂)²) +
// max((g₁-g₂)², (g₁-g₂ - a₁+a₂)²) +
// max((b₁-b₂)², (b₁-b₂ - a₁+a₂)²)
return MAX(pow(self.redComponent - color.redComponent, 2), pow(self.redComponent - color.redComponent - self.alphaComponent + color.alphaComponent, 2))
+ MAX(pow(self.greenComponent - color.greenComponent, 2), pow(self.greenComponent - color.greenComponent - self.alphaComponent + color.alphaComponent, 2))
+ MAX(pow(self.blueComponent - color.blueComponent, 2), pow(self.blueComponent - color.blueComponent - self.alphaComponent + color.alphaComponent, 2));
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment