ios - 在iOS中合并两个PNG UIImage,而不会失去透明度

标签 ios objective-c

我有两个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;
}

需要任何帮助来改善我的代码的性能。

提前致谢

最佳答案

首先,这些对CGContextSaveGStateCGContextRestoreGState的调用,一个接一个,一个之间接一个,没有为您做任何事情。请参阅此其他答案以了解CGContextSaveGStateCGContextRestoreGState的功能:CGContextSaveGState vs UIGraphicsPushContext

现在,我还不是100%清楚“合并”图像的含义。如果您只想在另一个上画一个,并使用标准的混合模式来混合它们的颜色,则只需更改这些混合模式调用即可传递kCGBlendModeNormal(或完全忽略对CGContextSetBlendMode的调用。)用第一张图像的Alpha值遮盖第二张图像,然后应使用普通混合模式绘制第二张图像,然后切换到kCGBlendModeDestinationIn并绘制第一张图像。

恐怕我不太确定您在尝试使用中间的图像着色代码做什么,但是我的直觉是您最终不会需要它。通过绘制一张图像,然后设置混合模式,再绘制另一张图像,您应该能够获得最大的合并效果。

另外,您在注释“绘制白色背景以保留透明像素的颜色”下找到的代码可能会在整个图像中绘制白色,但是它肯定不会保留透明像素的颜色,而是使这些像素变为白色!除非您确实希望您的“透明”颜色为白色,否则您也应该删除该代码。

关于ios - 在iOS中合并两个PNG UIImage,而不会失去透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16820439/

相关文章:

ios - iOS ShareExtension 应用程序中的数据共享问题

objective-c - 如何从另一个 View Controller 呈现一个 View Controller

ios - 如何在 React 应用程序中使用 Swift View Controller ?

objective-c - 简单的 NSMutable 数组问题

objective-c - 在ubuntu的GNUStep中编译Objective c时出错

ios - Codesign 和 Ambiguous identity,匹配 "Mac Developer"和 "iPhone Developer"

ios - 无法遍历数组

iphone - 如何在 iPhone 上以编程方式绘制椭圆形气泡?

ios - 当应用程序在收到推送通知后变为事件状态时,在主 ViewController 上触发事件

ios - 如何使 UISearchBar Objective C 向 API 请求信息并重新填充 TableViewController。?