ios - 如何去除不透明度但保留 UIImage 的 alpha channel ?

标签 ios uiimage mask blend cgimage

我有一个图层,我希望用户在其中绘制一个“ mask ”以剪切图像。它是半透明的,因此他们可以看到所选内容的下方。

我如何处理它,使绘图数据的 alpha 为 1.0,但保留 alpha channel (用于 mask )?

TL:DR - 我希望黑色区域是单一的纯色。

  • 这是所需的之前和之后(两者的白色背景都应该是透明的): Desired Before & After

像这样:

for (pixel in image) {
  if (pixel.alpha != 0.0) {
    fill solid black
  }
}

最佳答案

以下内容应该可以满足您的需求。大部分代码来自 How to set the opacity/alpha of a UIImage?在将像素的颜色转换为黑色之前,我只添加了对 alpha 值的测试。

// Create a pixel buffer in an easy to use format
CGImageRef imageRef = [[UIImage imageNamed:@"testImage"] CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

UInt8 * m_PixelBuf = malloc(sizeof(UInt8) * height * width * 4);

NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(m_PixelBuf, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);

//alter the alpha when the alpha of the source != 0
int length = height * width * 4;
for (int i=0; i<length; i+=4) {
  if (m_PixelBuf[i+3] != 0) {
    m_PixelBuf[i+3] = 255;
  }
}

//create a new image
CGContextRef ctx = CGBitmapContextCreate(m_PixelBuf, width, height,
                                         bitsPerComponent, bytesPerRow, colorSpace,
                                         kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

CGImageRef newImgRef = CGBitmapContextCreateImage(ctx);
CGColorSpaceRelease(colorSpace);
CGContextRelease(ctx);
free(m_PixelBuf);

UIImage *finalImage = [UIImage imageWithCGImage:newImgRef];
CGImageRelease(newImgRef);

finalImage 现在将包含一个图像,其中所有不具有 alpha 0.0 的像素都具有 alpha 1。

关于ios - 如何去除不透明度但保留 UIImage 的 alpha channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26704715/

相关文章:

ios - xcode图像位置x y实时更新

ios - 如何在ios中将字节数组转换为图像

ios - 如何在 iOS 7 的 UITextField 中添加带缩进的图像 UIImage?

objective-c - 以 Retina 质量屏蔽 2 个 UIImages

iphone - iOS 应用程序崩溃,出现与 _NSFastEnumerationMutationHandler 相关的异常

android - 在没有互联网的情况下唤醒锁定的手机

performance - 优化-webkit-transform 性能的技巧?

ios - UIImageView,从远程 URL 加载 UIImage

matlab - 如何计算拉普拉斯掩模或任何尺寸

python - 如何在 opencv 2.4.11 python 中调整轮廓大小? (目标 : Object extraction)