UIImage混合模式问题

时间:2012-07-15 05:54:44

标签: objective-c ios xcode uiimage blend

我正在尝试覆盖2张图片。底部图像从图像库加载到UIImageView对象,其alpha设置为1.0。此图像中的所有像素的alpha值也为1.0。我在上下文中创建的第二个图像。此图像的alpha值因像素而异。在上下文中创建第二个图像后,我将其绘制到第一个UIImageView顶部显示的第二个UIImageView。第二个UIImageView的alpha设置为1.0。两个UIImageView都将background属性设置为clear。

我正在尝试使用滑块在运行时更改第二个图像中像素的各个alpha值,但是,我无法使第二个图像的RGB值与第一个图像正确混合。我不想基于亮度,黑暗等进行混合。似乎我想要kCGBlendModeCopy,但这似乎仍然基于亮度或其他参数进行混合。

帮助可视化问题:想象一下我的底部UIImageView是一个人的照片。我的顶级UIImageView由2个实心分隔的圆圈组成; 1红色和1绿色。使用滑块,如果我将红色像素的alpha值从0.0更改为1.0并返回,则红色圆圈应淡入红色,淡入淡出。

我可以通过将RGB数据数组值设置为等于alpha值并将alpha值设置为1.0来验证我的alpha值是否正常工作。这显示黑色圆圈渐渐变白和背面。

这是我用来创建第一个覆盖在第一个图像上的代码。

//image <-- is the name of the second UIImageView that's passed to this method
//rgbaDataNew <-- is the name of my pixel data array for the second image

CGContextRef context;
CGImageRef imageRef;    
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

context = CGBitmapContextCreate(rgbaDataNew, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 
imageRef = CGBitmapContextCreateImage (context);
UIImage * topImage = [UIImage imageWithCGImage:imageRef];

CGContextSetBlendMode(context, kCGBlendModeCopy);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), [topImage CGImage]);

image.image = [UIImage imageWithCGImage:CGBitmapContextCreateImage (context)];

CGColorSpaceRelease(colorSpace);    
CGContextRelease(context);  
CGImageRelease(imageRef);

1 个答案:

答案 0 :(得分:0)

我会以稍微不同的方式攻击这个问题,但它会涉及做少量的Quartz工作。

创建一个UIView子类并添加第一个imageView作为属性,还添加一些其他值来定义你想要用叠加层做什么。

在子类的drawRect中,首先使用UIImageView的 - (void)drawInRect:(CGRect)rect方法绘制图像。

然后,您可以使用石英在图像上精确地绘制对象(使用视图的属性,为您提供框架,颜色,不透明度等。您可以使用Quartz轻松找到示例代码。

或者,如果你真的想使用第二个imageView,那么你可以在绘制底部视图后使用第二个视图 - (void)drawInRect:(CGRect)rect blendMode:(CGBlendMode)blendMode alpha:(CGFloat)覆盖它的alpha方法。

在任何一种情况下,您都使用UIView子类。