Pergunta

I am trying to identify some pixel colors, but I don't think I am clear to what people are doing. I've seen many sample codes around here and google, but I think I am missing something.

Here's how I am calling the method:

app.h

UIImage *image;

app.m

- (id)init {

    self = [super init];
    if(self) {
...
image = [UIImage imageNamed:@"bwimage.bmp"];
...

[self checkRailBW:image :x_pos :y_pos]

...

Here's the method:

-(BOOL)checkRailBW: (UIImage*)background : (CGFloat)x : (CGFloat)y{


CGImageRef image = background.CGImage;
NSUInteger width = CGImageGetWidth(background);
NSUInteger height = CGImageGetHeight(background);

// Setup 1x1 pixel context to draw into
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char rawData[4];
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData,
                                             1,
                                             1,
                                             bitsPerComponent,
                                             bytesPerRow,
                                             colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy);

// Draw the image
CGContextDrawImage(context,
                   CGRectMake(x, y-height, width, height),
                   image);

// Done
CGContextRelease(context);

// Get the pixel information
unsigned char red   = rawData[0];
unsigned char green = rawData[1];
unsigned char blue  = rawData[2];
unsigned char alpha = rawData[3];
}

I can never get any data on Red, Green or Blue.

By the way... I am tracing black pixels. I am working on a black&white image, so it would have 1 bit/pixel.

Thanks for the hand!

Foi útil?

Solução

You're always drawing the upper left pixel of the image into your 1x1 context. You need to either change the origin of the CGRect you're making to draw the pixel you want in the right location, or set up the current transformation matrix to offset where drawing happens so that the pixel in question lands on the origin of your context.

But you probably shouldn't do either of those, since this is a super inefficient way to get what you want. What are you actually trying to do here? You obviously want the color of a pixel in the image, but for what purpose? Are you iterating over all pixels in the image? If so, you should probably draw the image into a bitmap once, and then use pointer arithmetic to get at the pixel you want to test.

Or if you're trying to in some way modify the pixels, you should use some other tool, such as CoreImage, or OpenGL.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top