CoreGraphics - CGImage:获取特定像素的颜色

时间:2012-12-19 01:57:05

标签: objective-c core-graphics cgcontext cgimage

我尝试计算图像中黑/白部分的百分比。但是,我的结果不是逻辑。看看:

unsigned char *data = CGBitmapContextGetData(contextMask);
int offset = 0;

if (data == NULL)
{
    return 0.0;
}

float sum = 0.0;

for (int x = 0; x < CGImageGetWidth(scratchImage); x++)
{
    for (int y = 0; y < CGImageGetHeight(scratchImage); y++)
    {
        NSLog(@"Offset %d,%d: %hhu", x, y, data[offset+1]);
        if (data[offset+1] == 0)
        {
           sum = sum + 1;
        }

        offset += 4;
    }
}

图像只有黑白两色,有时我的数字介于0到255之间。你有什么想法吗?非常感谢你。

这就是CGImage的创建方式:

CFMutableDataRef pixels = CFDataCreateMutable(NULL, imageWidth * imageHeight);
contextMask = CGBitmapContextCreate(CFDataGetMutableBytePtr(pixels),
         imageWidth, imageHeight, 8, imageWidth, colorspace, kCGImageAlphaNone);

CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData(pixels);

CGContextSetFillColorWithColor(contextMask, [UIColor blackColor].CGColor);
CGContextFillRect(contextMask, self.frame);

CGContextSetStrokeColorWithColor(contextMask, [UIColor whiteColor].CGColor);
CGContextSetLineWidth(contextMask, _sizeBrush);
CGContextSetLineCap(contextMask, kCGLineCapRound);

CGImageRef mask = CGImageMaskCreate(imageWidth, imageHeight, 8, 8, imageWidth,
                                                       dataProvider, nil, NO);
scratchImage = CGImageCreateWithMask(hideImage, mask);

0 个答案:

没有答案