How do I check if CGContext contains point?

和自甴很熟 提交于 2019-12-02 09:22:38

AFAIK there is no easy way to get color of some point in CGContext. But you can use approach described here http://www.markj.net/iphone-uiimage-pixel-color/

I have not tested this code but I hope it works or is easy to fix:

// ctxSize - is a size of context
- (UIColor*) getPixelColorForContext:(CGContextRef)cgctx size:(CGSize)ctxSize atLocation:(CGPoint)point
{
    UIColor* color = nil;
    // Create off screen bitmap context to draw the image into. Format ARGB is 4 bytes for each pixel: Alpa, Red, Green, Blue
    if (cgctx == NULL) { return nil; /* error */ }

    size_t w = ctxSize.width;

    // Now we can get a pointer to the image data associated with the bitmap
    // context.
    unsigned char* data = CGBitmapContextGetData (cgctx);
    if (data != NULL) {
        //offset locates the pixel in the data from x,y. 
        //4 for 4 bytes of data per pixel, w is width of one row of data.
        int offset = 4*((w*round(point.y))+round(point.x));
        int alpha =  data[offset]; 
        int red = data[offset+1]; 
        int green = data[offset+2]; 
        int blue = data[offset+3]; 
        NSLog(@"offset: %i colors: RGB A %i %i %i  %i",offset,red,green,blue,alpha);
        color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
    }

    // Free image data memory for the context
    if (data) { free(data); }

    return color;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!