简体   繁体   中英

How to get the coordinates of each pixel of custom uiimage?

Hi everyone

I need to write the simple puzzle game and the main condition is that when the piece of puzzle is close to its destination when it is "released" it gets there exactly where it should be.

So I tried to get the array of cordinates of each pixel of image, to do this I want to compare the pixels color with background color and if them are not equal, that is the coordinate of images pixel. But.. I don`t how to do this.

I tried:

- (BOOL)isImagePixel:(UIImage *)image withX:(int)x andY:(int) y {

    CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
    const UInt8* data = CFDataGetBytePtr(pixelData);

    int pixelInfo = ((image.size.width  * y) + x ) * 4; // The image is png

    UInt8 red = data[pixelInfo];         
    UInt8 green = data[(pixelInfo + 1)]; 
    UInt8 blue = data[pixelInfo + 2];    
    UInt8 alpha = data[pixelInfo + 3];   
    CFRelease(pixelData);

    UIColor* color = [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.0f]; 

        NSLog(@"color is %@",[UIColor whiteColor]);
    if ([color isEqual:self.view.backgroundColor]){
        NSLog(@"x = %d, y = %d",x,y);
        return YES;
    }
    else return NO;

}

What is wrong here?
Or maybe someone can suggest me another solution?

Thank you.

This appears to be a really cumbersome solution. My suggestion is that for every piece you maintain a table of say it's top left coordinate in the puzzle, and when the user lifts a finger you compute the absolute distance from the current location to the designated location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM