2016-01-25 191 views
0

我有兩個透明背景的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; 

,但它與白色背景返回一個圖像。

任何想法,爲什麼,請?

+0

與'CGContextSaveGState'&'CGContextRestoreGState'功能相鄰的是什麼?您需要在更改狀態之前保存狀態,然後再恢復。 – Hamish

+0

我是CGContext&UIGraphics的新手,我在這裏找到了這段代碼,但是不起作用。但是,感謝您的回覆 – ankmara

+1

您似乎已經複製併合並了隨機代碼。你爲什麼使用'kCGBlendModeDarken'和'kCGBlendModeDarken'。你爲什麼設置和恢復圖形狀態?不要只複製你找到的代碼。你需要知道它做了什麼。這個問題並不難。這似乎很難,因爲你在做些隨意的事情。 –

回答

1

如果你的兩幅圖像都有透明度,那麼用正常的混合模式繪製它們都不會以任何方式「失去」透明度。

你就應該能夠得出一個在另一個之上:

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; 

你也不需要保存和恢復上下文的圖形狀態(至少所有外繪圖),除非您要重用上下文。

+0

你救了我,謝謝 – ankmara

+0

不用擔心!如果你想在Core Graphics上做進一步的工作,我強烈建議你閱讀Quartz 2D文檔:https://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_overview/dq_overview。 HTML#// apple_ref/DOC/UID/TP30001066-CH202-TPXREF101。 Ray Wenderlich也有一些很好的教程:http://www.raywenderlich.com/tag/core-graphics – Hamish

0

我不很瞭解這個問題,但讓我們來試試......

嘗試設置圖,其中圖像將與setOpaque像波紋管例如...

[self.thatView setOpaque:NO] 

希望有所幫助。