CGContext中的alpha像素数 [英] Number of alpha pixels in CGContext

查看:110
本文介绍了CGContext中的alpha像素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个屏蔽 CGContext ,有两种类型的像素:颜色和alpha(不透明和透明像素)。如何在我的上下文中计算alpha像素的百分比?

I have a masking CGContext with 2 types of pixels: color and alpha (opaque and transparent pixels). How to calculate percentage of alpha pixels in my context?

推荐答案

我没有测试它,但这应该可以做到 - 只需传递ReportAlphaPercent一个CGImageRef:

I didn't test it, but this should do the trick - just pass ReportAlphaPercent a CGImageRef:

UIImage *foo; //The image you want to analyze
float alphaPercent = ReportAlphaPercent(foo.CGImage);


float ReportAlphaPercent(CGImageRef imgRef)
{
    size_t w = CGImageGetWidth(imgRef);
    size_t h = CGImageGetHeight(imgRef);

    unsigned char *inImage = malloc(w * h * 4);
    memset(inImage, 0, (h * w * 4));

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(inImage, w, h, 8, w * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGContextSetShouldAntialias(context, NO);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), imgRef);

    int byteIndex = 0;

    int alphaCount = 0;

    for(int i = 0; i < (w * h); i++) {

        if (inImage[byteIndex + 3]) { // if the alpha value is not 0, count it
            alphaCount++;
        }

        byteIndex += 4;
    }

    free(inImage);

    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    return (float) alphaCount / (w * h);
}

这篇关于CGContext中的alpha像素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆