我有一个图层,我希望用户在其中绘制一个“ mask ”以剪切图像。它是半透明的,因此他们可以看到所选内容的下方。
我如何处理它,使绘图数据的 alpha 为 1.0,但保留 alpha channel (用于 mask )?
TL:DR - 我希望黑色区域是单一的纯色。
- 这是所需的之前和之后(两者的白色背景都应该是透明的):
像这样:
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/