react-native-get-pixel_edit/ios/PNGetPixel/UIImage+RGBAAtPixel.m
2025-07-09 11:41:52 +09:00

48 lines
1.9 KiB
Objective-C

#import <CoreGraphics/CoreGraphics.h>
#import "UIImage+RGBAAtPixel.h"
@implementation UIImage (RGBAAtPixel)
- (BOOL)rgbaAtPixel:(CGPoint)point
red:(CGFloat*)red
green:(CGFloat*)green
blue:(CGFloat*)blue {
// Cancel if point is outside image coordinates
if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point)) {
return NO;
}
// Create a 1x1 pixel byte array and bitmap context to draw the pixel into.
// Reference: http://stackoverflow.com/questions/1042830/retrieving-a-pixel-alpha-value-for-a-uiimage
NSInteger pointX = point.x;
NSInteger pointY = point.y;
CGImageRef cgImage = self.CGImage;
NSUInteger width = self.size.width;
NSUInteger height = self.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * 1;
NSUInteger bitsPerComponent = 8;
unsigned char pixelData[4] = { 0, 0, 0, 0 };
CGContextRef context = CGBitmapContextCreate(pixelData,
1,
1,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy);
CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
CGContextRelease(context);
*red = (CGFloat)pixelData[0];
*green = (CGFloat)pixelData[1];
*blue = (CGFloat)pixelData[2];
return YES;
}
@end