Skip to content

Instantly share code, notes, and snippets.

@StephanPartzsch
Last active March 19, 2020 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephanPartzsch/0ab2fd4755335c7cccaa to your computer and use it in GitHub Desktop.
Save StephanPartzsch/0ab2fd4755335c7cccaa to your computer and use it in GitHub Desktop.
[Extract UIColor] Extract UIColor value at a specific point in a given UIImage (#UI)
- (UIColor *)colorForImage:(UIImage *)image atPoint:(CGPoint)point
{
CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
CFDataRef pixelData = CGDataProviderCopyData(provider);
const UInt8* data = CFDataGetBytePtr(pixelData);
int numberOfColorComponents = 4; // R,G,B, and A
float positionX = point.x;
float positionY = point.y;
float imageWidth = image.size.width;
int pixelInfo = (int)((imageWidth * positionY) + positionX) * numberOfColorComponents;
UInt8 red = data[pixelInfo];
UInt8 green = data[(pixelInfo + 1)];
UInt8 blue = data[pixelInfo + 2];
UInt8 alpha = data[pixelInfo + 3];
CFRelease(pixelData);
return [UIColor colorWithRed: red/255.0f
green:green/255.0f
blue:blue/255.0f
alpha:alpha/255.0f];
}
@StephanPartzsch
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment