0

I want to know the color of all the pixel and want to return an array of it. This is how I am doing it so far:

- (NSMutableArray *) colorOfPointinArray{

    NSMutableArray *array_of_colors=[[NSMutableArray alloc] init];
    unsigned char pixel[4]={0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast);
    for (int x_axis=0; x_axis<screenWidth; x_axis++)
    {
        for (int y_axis=0; y_axis<screenHeight; y_axis++)
        {
            CGContextTranslateCTM(context, -x_axis, -y_axis);
            [self.layer renderInContext:context];

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

            [array_of_colors addObject:color];
        }
    }
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    return array_of_colors;
}

Now, this is taking so much time and freezes the app. I think its because of the 2 for-loops I have added. How can I improve this ?

rdurand
  • 7,342
  • 3
  • 39
  • 72
Funny
  • 566
  • 5
  • 16

2 Answers2

0

You're creating a 1x1 pixel context, and then rendering the image into that one pixel h*w times. No wonder it's taking forever! Instead, create a context that's the same size as the layer, and then render into that context just once. Then loop through the resulting pixels and keep the color values. This may still not be instantaneous; depending on the size of the layer, turning every pixel into a UIColor could still take awhile (and some nontrivial memory) but that'll be about as quick as you can get it in the general case if you really want output in that form.

Ben Zotto
  • 70,108
  • 23
  • 141
  • 204
0

This is similar to the problem of sampling a pixel color value from an image. There are tons of posts about that. This one has some nice examples: How to get the RGB values for a pixel on an image on the iphone

Community
  • 1
  • 1
Anna Dickinson
  • 3,307
  • 24
  • 43