ios像素检测点击

来源:互联网 发布:纯甘油兑水比例知乎 编辑:程序博客网 时间:2024/05/19 14:20

出处:http://www.cocoachina.com/bbs/read.php?tid=115082&fpage=35

可用作不规则图像的单击问题。

1、透明偏移

NSUInteger alphaOffset(NSUInteger x, NSUInteger y, NSUInteger w){return y * w * 4 + x * 4 + 0;}

2、得到png图片字符数组值
unsigned char *getBitmapFromImage (UIImage *image)
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL)
    {
        fprintf(stderr, "Error allocating color space\n");
        return NULL;
    }
    
    CGSize size = image.size;
    // void *bitmapData = malloc(size.width * size.height * 4);
    unsigned char *bitmapData = calloc(size.width * size.height * 4, 1); // Courtesy of Dirk. Thanks!
    if (bitmapData == NULL)
    {
        fprintf (stderr, "Error: Memory not allocated!");
        CGColorSpaceRelease(colorSpace);
        return NULL;
    }
    
    CGContextRef context = CGBitmapContextCreate (bitmapData, size.width, size.height, 8, size.width * 4, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGColorSpaceRelease(colorSpace );
    if (context == NULL)
    {
        fprintf (stderr, "Error: Context not created!");
        free (bitmapData);
        return NULL;
    }
    
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    CGContextDrawImage(context, rect, image.CGImage);
    unsigned char *data = CGBitmapContextGetData(context);
    CGContextRelease(context);
    
    return data;
}

// 测试是否点击到png的不透明部分
- (BOOL) pointInside:(CGPoint)point withEvent:(UIEvent *)event 
{
    if (!CGRectContainsPoint(self.bounds, point)) return NO;
    return (bytes[alphaOffset(point.x, point.y, self.image.size.width)] > 85);
}