[英]merge two transparent images without lose transparency
我有兩個透明背景的PNG圖片。 我需要將它們合並為一張圖像而不會丟失透明背景。
我用了這段代碼
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;
但它會返回一張帶有白色背景的圖像。
知道為什么嗎?
如果兩個圖像都具有透明性,則使用普通的混合模式繪制它們都不會“失去”透明度。
您應該能夠在另一個之上繪制一個:
UIGraphicsBeginImageContext(firstImage.size); // Assumes the first image is the same size as the second image.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, firstImage.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, rect, firstImage.CGImage);
CGContextDrawImage(context, rect, secondImage.CGImage);
UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return coloredImage;
您也不需要保存和恢復上下文的圖形狀態(至少在所有圖形之外),除非您要重用上下文。
我對這個問題不太了解,但請嘗試...
嘗試使用setOpaque設置圖像在其中的視圖,例如下面的示例...
[self.thatView setOpaque:NO]
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.