ios – 如何将UIImage / CGImageRef的Alpha通道转换为掩码?

前端之家收集整理的这篇文章主要介绍了ios – 如何将UIImage / CGImageRef的Alpha通道转换为掩码?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何提取UI Image或CG ImageRef的Alpha通道,并将其转换为可与CGImageMaskCreate一起使用的掩码?

例如:

基本上,给出任何图像,我不关心图像中的颜色.我想要的是创建一个表示Alpha通道的灰度图像.然后可以使用该图像来屏蔽其他图像.

当您提供图标图像时,其示例行为在UIBarButtonItem中.根据苹果文档,它表示:

The images displayed on the bar are derived from this image. If this image is too large to fit on the bar,it is scaled to fit. Typically,the size of a toolbar and navigation bar image is 20 x 20 points. The alpha values in the source image are used to create the images—opaque values are ignored.

UIBarButtonItem接受任何图像,只能看到alpha,而不是图像的颜色.

解决方法

要按条形按钮项目的方式来绘制图标,您不需要传统的面具,您想要一个面具的倒数 – 原始图像中的不透明像素占用最终着色,而不是其他方式.

这是完成这个的一种方法.拿你原来的RBGA图像,并通过以下处理:

>将其绘制为仅Alpha通道位图图像
>反转每个像素的alpha值得到与上述相反的行为
>将此倒置的Alpha图像转换为实际的掩码
>使用它

例如.

#define ROUND_UP(N,S) ((((N) + (S) - 1) / (S)) * (S))

// Original RGBA image
CGImageRef originalMaskImage = [[UIImage imageNamed:@"masktest.png"] CGImage];
float width = CGImageGetWidth(originalMaskImage);
float height = CGImageGetHeight(originalMaskImage);

// Make a bitmap context that's only 1 alpha channel
// WARNING: the bytes per row probably needs to be a multiple of 4 
int strideLength = ROUND_UP(width * 1,4);
unsigned char * alphaData = calloc(strideLength * height,sizeof(unsigned char));
CGContextRef alphaOnlyContext = CGBitmapContextCreate(alphaData,width,height,8,strideLength,NULL,kCGImageAlphaOnly);

// Draw the RGBA image into the alpha-only context.
CGContextDrawImage(alphaOnlyContext,CGRectMake(0,height),originalMaskImage);

// Walk the pixels and invert the alpha value. This lets you colorize the opaque shapes in the original image.
// If you want to do a traditional mask (where the opaque values block) just get rid of these loops.
for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
        unsigned char val = alphaData[y*strideLength + x];
        val = 255 - val;
        alphaData[y*strideLength + x] = val;
    }
}

CGImageRef alphaMaskImage = CGBitmapContextCreateImage(alphaOnlyContext);
CGContextRelease(alphaOnlyContext);
free(alphaData);

// Make a mask
CGImageRef finalMaskImage = CGImageMaskCreate(CGImageGetWidth(alphaMaskImage),CGImageGetHeight(alphaMaskImage),CGImageGetBitsPerComponent(alphaMaskImage),CGImageGetBitsPerPixel(alphaMaskImage),CGImageGetBytesPerRow(alphaMaskImage),CGImageGetDataProvider(alphaMaskImage),false);
CGImageRelease(alphaMaskImage);

现在,您可以使用finalMaskImage作为CGContextClipToMask等中的掩码等.

猜你在找的iOS相关文章