iphone - CGContext 中的 alpha 像素数

标签 iphone ios core-graphics cgcontext

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

最佳答案

我没有测试它,但这应该可以解决问题 - 只需将 ReportAlphaPercent 传递给 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);
}

关于iphone - CGContext 中的 alpha 像素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8992522/

相关文章:

ios - 如何获取ios应用程序窗口的顶部栏高度?

ios - 使用宽高比调整 UIImage 的大小?

iphone - UIView动画的问题

iphone - iPhone 中调用某些 CTFunction 时出现内存泄漏

iphone - 在 iPhone 和 Android 上生成二维条码(例如 QR 码、数据矩阵、PDF417)

iphone - 如何使用 OpenAL 即时生成和播放白噪声?

ios - 使用 Swift 在音乐播放器应用程序中设置音乐播放 slider ?

objective-c - 委托(delegate) - 如何使用?

iphone - 字符串开头的 RegexKitLite 问题

iphone - 全屏背景纹理与 OpenGL 性能问题 (iPad)