时间:2011-01-06 15:51:44

标签: ios colors screen pixel

3 个答案:

答案 0 :(得分:8)

答案 1 :(得分:5)

以下是如何操作

CGContextRef ctx;
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);

//GET PIXEL FROM POINT
int index = 4*((width*round(yCoor))+round(xCoor));

int R = rawData[index];
int G = rawData[index+1];
int B = rawData[index+2];

NSLog(@"%d   %d   %d", R, G, B);

//IF YOU WANT TO ALTER THE PIXELS

int byteIndex = 0;

for(int ii = 0 ; ii < width * height ; ++ii)
{ 
    rawData[byteIndex] = (char)(newPixelValue);
    rawData[byteIndex+1] = (char)(newPixelValue);
    rawData[byteIndex+2] = (char)(newPixelValue);

    byteIndex += 4;
}


ctx = CGBitmapContextCreate(rawData,
                            CGImageGetWidth( imageRef ),
                            CGImageGetHeight( imageRef ),
                            8,
                            CGImageGetBytesPerRow( imageRef ),
                            CGImageGetColorSpace( imageRef ),
                            kCGImageAlphaPremultipliedLast ); 

imageRef = CGBitmapContextCreateImage(ctx);
UIImage* rawImage = [UIImage imageWithCGImage:imageRef];  

CGContextRelease(ctx);  

image = rawImage;  

free(rawData);

答案 2 :(得分:0)

试试这个“self.m_imgvwSource”根据您的需要是uiview / uiimageview

- (UIColor *) GetCurrentPixelColorAtPoint:(CGPoint)point
{
    unsigned char pixel[4] = {0};

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast);

    CGContextTranslateCTM(context, -point.x, -point.y);

    [self.m_imgvwSource.layer renderInContext:context];

    CGContextRelease(context);

    CGColorSpaceRelease(colorSpace);

    NSLog(@"pixel: %d %d %d %d", pixel[0], pixel[1], pixel[2], pixel[3]);

    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];

    return color;
}