我有两个png格式的图像,并且都定义了透明度。我需要将这些合并到一个新的png图像中,但又不损失结果的任何透明度。
+(UIImage *) combineImage:(UIImage *)firstImage colorImage:(UIImage *)secondImage
{
UIGraphicsBeginImageContext(firstImage.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, firstImage.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGRect rect = CGRectMake(0, 0, firstImage.size.width, firstImage.size.height);
// draw white background to preserve color of transparent pixels
CGContextSetBlendMode(context, kCGBlendModeDarken);
[[UIColor whiteColor] setFill];
CGContextFillRect(context, rect);
CGContextSaveGState(context);
CGContextRestoreGState(context);
// draw original image
CGContextSetBlendMode(context, kCGBlendModeDarken);
CGContextDrawImage(context, rect, firstImage.CGImage);
// tint image (loosing alpha) - the luminosity of the original image is preserved
CGContextSetBlendMode(context, kCGBlendModeDarken);
//CGContextSetAlpha(context, .85);
[[UIColor colorWithPatternImage:secondImage] setFill];
CGContextFillRect(context, rect);
CGContextSaveGState(context);
CGContextRestoreGState(context);
// mask by alpha values of original image
CGContextSetBlendMode(context, kCGBlendModeDestinationIn);
CGContextDrawImage(context, rect, firstImage.CGImage);
// image drawing code here
CGContextRestoreGState(context);
UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return coloredImage;
}
需要任何帮助来改善我的代码的性能。
提前致谢
最佳答案
首先,这些对CGContextSaveGState
和CGContextRestoreGState
的调用,一个接一个,一个之间接一个,没有为您做任何事情。请参阅此其他答案以了解CGContextSaveGState
和CGContextRestoreGState
的功能:CGContextSaveGState vs UIGraphicsPushContext
现在,我还不是100%清楚“合并”图像的含义。如果您只想在另一个上画一个,并使用标准的混合模式来混合它们的颜色,则只需更改这些混合模式调用即可传递kCGBlendModeNormal
(或完全忽略对CGContextSetBlendMode
的调用。)用第一张图像的Alpha值遮盖第二张图像,然后应使用普通混合模式绘制第二张图像,然后切换到kCGBlendModeDestinationIn
并绘制第一张图像。
恐怕我不太确定您在尝试使用中间的图像着色代码做什么,但是我的直觉是您最终不会需要它。通过绘制一张图像,然后设置混合模式,再绘制另一张图像,您应该能够获得最大的合并效果。
另外,您在注释“绘制白色背景以保留透明像素的颜色”下找到的代码可能会在整个图像中绘制白色,但是它肯定不会保留透明像素的颜色,而是使这些像素变为白色!除非您确实希望您的“透明”颜色为白色,否则您也应该删除该代码。
关于ios - 在iOS中合并两个PNG UIImage,而不会失去透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16820439/