获取UIImageView CGPoints

时间:2015-03-08 14:14:04

标签: objective-c iphone uiimageview uicolor cgpoint

我想获得UIImageVeiw中的所有积分,所以我可以改变一些"一些"点颜色而不需要UITouch ..是否可能?

我在想的是:

  1. 获取uiimageview中的所有积分
  2. 获得每个点的颜色。
  3. 如果前一种颜色=某种特定颜色,则更改颜色。
  4. 我搜索了很多,但我发现所有的教程都依赖于UITouch这样http://www.markj.net/iphone-uiimage-pixel-color/

    我现在的主要目标是如何获得所有积分?!

    感谢任何帮助

1 个答案:

答案 0 :(得分:0)

我找到了解决方案..希望有一天能帮到任何人。 此方法返回某些图像中的像素数组。

-(NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)x andY:(int)y count:(int)count
{
   NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];

// First get the image into your data buffer
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
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);

// Now your rawData contains the image data in the RGBA8888 pixel format.
NSUInteger byteIndex = (bytesPerRow * y) + x * bytesPerPixel;
for (int i = 0 ; i < count ; ++i)
{
    CGFloat red   = (rawData[byteIndex]     * 1.0) / 255.0;
    CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
    CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0;
    CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
    byteIndex += bytesPerPixel;

    UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    [result addObject:acolor];
}

free(rawData);

return result;}
你可以这样称呼它:

NSArray*arrayOfPixels= [self getRGBAsFromImage:_patternFirstImage.image atX:_patternFirstImage.frame.origin.x andY:_patternFirstImage.frame.origin.y count:_patternFirstImage.frame.size.width*_patternFirstImage.frame.size.height];
NSLog(@"arrayOfPixels = %zd",[arrayOfPixels count]);

您可以遍历所有像素以获得其颜色,如下所示:

for(int i=0;i<[arrayOfPixels count];i++){
    NSLog(@"objects = ---%@----",[arrayOfPixels objectAtIndex:i]);
    if([self color:[arrayOfPixels objectAtIndex:i] isEqualToColor:UIColorFromRGB(0xE0E0E0) withTolerance:0.2]){
        NSLog(@"index = %zd",i);
    }
}

非常感谢答案: https://stackoverflow.com/a/1262893/2168496