Guest User

Untitled

a guest
Nov 17th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. - (UIColor *)colorAtPixel:(CGPoint)point {
  2. // Cancel if point is outside image coordinates
  3. if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, _overlay_imageView.frame.size.width, _overlay_imageView.frame.size.height), point)) {
  4. return nil;
  5. }
  6.  
  7.  
  8. // Create a 1x1 pixel byte array and bitmap context to draw the pixel into.
  9. // Reference: http://stackoverflow.com/questions/1042830/retrieving-a-pixel-alpha-value-for-a-uiimage
  10. NSInteger pointX = trunc(point.x);
  11. NSInteger pointY = trunc(point.y);
  12. CGImageRef cgImage = _overlay_imageView.image.CGImage;
  13. NSUInteger width = CGImageGetWidth(cgImage);
  14. NSUInteger height = CGImageGetHeight(cgImage);
  15. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  16. int bytesPerPixel = 4;
  17. int bytesPerRow = bytesPerPixel * 1;
  18. NSUInteger bitsPerComponent = 8;
  19. unsigned char pixelData[4] = { 0, 0, 0, 0 };
  20. CGContextRef context = CGBitmapContextCreate(pixelData,
  21. 1,
  22. 1,
  23. bitsPerComponent,
  24. bytesPerRow,
  25. colorSpace,
  26. kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
  27. CGColorSpaceRelease(colorSpace);
  28. CGContextSetBlendMode(context, kCGBlendModeCopy);
  29.  
  30. // Draw the pixel we are interested in onto the bitmap context
  31. CGContextTranslateCTM(context, -pointX, -pointY);
  32. CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
  33. CGContextRelease(context);
  34.  
  35. // Convert color values [0..255] to floats [0.0..1.0]
  36. CGFloat red = (CGFloat)pixelData[0] / 255.0f;
  37. CGFloat green = (CGFloat)pixelData[1] / 255.0f;
  38. CGFloat blue = (CGFloat)pixelData[2] / 255.0f;
  39. CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;
  40.  
  41. return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
  42. }
Add Comment
Please, Sign In to add comment