在iOS Cocoa中覆盖非透明像素

有没有什么办法在iOS SDK上覆盖彩色像素的图像中的非透明像素?


非常感谢两位回答。

我实现的最终解决scheme使用了接受的答案中的子类UIView的drawRect方法中提到的代码,我用下面的代码覆盖颜色:

CGContextSetFillColor(context, CGColorGetComponents([UIColor colorWithRed:0.5 green:0.5 blue:0 alpha:1].CGColor)); CGContextFillRect(context, area); 

我想你可能正在寻找混合模式kCGBlendModeSourceAtop 。 首先,将UIImage绘制到您的视图中。 然后用获取当前的graphics上下文

 CGContext currentCtx = UIGraphicsGetCurrentContext(); 

然后保存上下文状态,并设置混合模式:

 CGContextSaveGState(currentCtx); CGContextSetBlendMode(currentCtx, kCGBlendModeSourceAtop); 

然后你可以绘制任何你想要覆盖在UIImage的不透明像素上。 之后,只需重置上下文状态:

 CGContextRestoreGState(currentCtx); 

希望这可以帮助!

您可以修改如何使用混合模式绘制东西。 请参阅http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Reference/CGContext/Reference/reference.html%23//apple_ref/doc/c_ref/CGBlendMode ,以获取支持的混合模式的完整列表iOS上的核心graphics。 从你的描述中,我想你会对kCGBlendModeSourceIn感兴趣,它使用旧内容的alpha值作为掩码来绘制新的内容,或者kCGBlendModeSourceAtop ,它使用旧的内容的alpha作为掩码,在旧的内容使用新内容的alpha值作为掩码。 您可以使用CGContextSetBlendMode为所有绘图设置混合模式,也可以使用-[UIImage drawAtPoint:blendMode:alpha:]绘制具有特定混合模式的-[UIImage drawAtPoint:blendMode:alpha:]