如何检查 CGContext 是不是包含点?

Posted

技术标签:

【中文标题】如何检查 CGContext 是不是包含点?【英文标题】:How do I check if CGContext contains point?如何检查 CGContext 是否包含点? 【发布时间】:2014-05-01 21:14:22 【问题描述】:

基本上我有在触摸移动时绘制的图像。当我打开一个名为橡皮擦的按钮时,我希望它检测我绘制的上下文在触摸的位置是否不是黑色的。有没有办法做到这一点?

- (id)initWithFrame:(CGRect)frame

    self = [super initWithFrame:frame];
    if (self) 
        hue = 0.0;
        [self initContext:frame.size];
        framsize = frame.size;
    
    return self;


-(void)clear

    cacheContext = nil;
    cacheBitmap = nil;
    [self initContext:framsize];
    [self setNeedsDisplay];




- (BOOL) initContext:(CGSize)size 

    float scaleFactor = [[UIScreen mainScreen] scale];

    int bitmapByteCount;
    int bitmapBytesPerRow;

    // Declare the number of bytes per row. Each pixel in the bitmap in this
    // example is represented by 4 bytes; 8 bits each of red, green, blue, and
    // alpha.
    bitmapBytesPerRow = (size.width * 4);
    bitmapByteCount = (bitmapBytesPerRow * size.height)*scaleFactor*scaleFactor;

    // Allocate memory for image data. This is the destination in memory
    // where any drawing to the bitmap context will be rendered.
    cacheBitmap = malloc( bitmapByteCount );
    if (cacheBitmap == NULL)
        return NO;
    

    CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    cacheContext = CGBitmapContextCreate (cacheBitmap, size.width*scaleFactor, size.height *scaleFactor, 8, bitmapBytesPerRow*scaleFactor, colorSpace, bitmapInfo);

    CGContextScaleCTM(cacheContext, scaleFactor, scaleFactor);
       CGColorSpaceRelease(colorSpace);

  CGContextSetRGBFillColor(cacheContext, 1, 0, 0, 0.0);
   CGContextFillRect(cacheContext, (CGRect)CGPointZero, CGSizeMake(size.height*scaleFactor, size.width*scaleFactor));

    return YES;


//-(float) alphaAtX:(int)x y:(int)y   //get alpha component using the pointer 'pixelData'
//
   // float scaleFactor = [[UIScreen mainScreen] scale];

  //  return pixelData[(y * 320*scaleFactor + x) *4 + 3];   //+0 for red, +1 for green, +2 for blue, +3 for alpha
//

-(UIColor *) colorOfPoint:(CGPoint)point

    unsigned char pixel[4] = 0;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel,
                                                 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);

    CGContextTranslateCTM(context, -point.x, -point.y);

    [self.layer renderInContext:context];

    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0
                                     green:pixel[1]/255.0 blue:pixel[2]/255.0
                                     alpha:pixel[3]/255.0];
    return color;


- (void) drawToCache:(CGPoint)currentpos andLastPos:(CGPoint)pos Color:(UIColor *)colors Thickness:(float)thickness
    hue += 0.005;
    if(hue > 1.0) hue = 0.0;
    UIColor *color;
    if (!colors) 
    color = [UIColor colorWithHue:hue saturation:0.7 brightness:1.0 alpha:1.0];
     else 
        color = colors;
    

    CGContextSetStrokeColorWithColor(cacheContext, [color CGColor]);
    CGContextSetLineCap(cacheContext, kCGLineCapRound);
    CGContextSetLineWidth(cacheContext, 6+thickness);

    CGPoint lastPoint = currentpos;
    CGPoint newPoint = lastPoint;

    CGContextMoveToPoint(cacheContext, lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(cacheContext, newPoint.x, newPoint.y);
    CGContextStrokePath(cacheContext);

    CGRect dirtyPoint1 = CGRectMake(lastPoint.x-10, lastPoint.y-10, 20, 20);
    CGRect dirtyPoint2 = CGRectMake(newPoint.x-10, newPoint.y-10, 20, 20);
    [self setNeedsDisplayInRect:CGRectUnion(dirtyPoint1, dirtyPoint2)];


- (void) drawRect:(CGRect)rect 
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGImageRef cacheImage = CGBitmapContextCreateImage(cacheContext);
    CGContextDrawImage(context, self.bounds, cacheImage);
    CGImageRelease(cacheImage);


@end

【问题讨论】:

我已经用代码示例更新了我的答案。你能检查一下吗? 【参考方案1】:

AFAIK 没有简单的方法来获取 CGContext 中某个点的颜色。但是你可以使用这里描述的方法http://www.markj.net/iphone-uiimage-pixel-color/

我没有测试过这段代码,但我希望它可以工作或者很容易修复:

// 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;

【讨论】:

良好的链接认为我没有使用任何图像,只是位图。你能告诉我没有图片我该怎么做吗? @user3534757 我已经为你编写了代码。请检查。如果有效,请不要忘记接受答案! 似乎不起作用。如果您想查看整个代码,我已经更新了我的帖子。

以上是关于如何检查 CGContext 是不是包含点?的主要内容,如果未能解决你的问题,请参考以下文章

如何快速检查 url 字符串是不是包含一个单词?

Mongodb:如何检查一个点是不是包含在多边形中?

如何使用 CGContext 模糊线条的边缘

如何检查电子邮件是不是有效? [复制]

修改正则表达式以检查 sting 是不是在 jquery validate 中不包含电子邮件地址

如何使用 CGContext 方法清除旧数据的绘制?