How do I check if CGContext contains point?

前端 未结 1 1015
长情又很酷
长情又很酷 2021-01-26 00:26

Basically I have image that gets drawn when the touch is moved. When i toggle on a button called eraser I want it to detect if the context I have drawn is NOT black at the posit

相关标签:
1条回答
  • 2021-01-26 01:16

    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;
    }
    
    0 讨论(0)
提交回复
热议问题