我有兩個透明背景的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;
,但它與白色背景返回一個圖像。
任何想法,爲什麼,請?
與'CGContextSaveGState'&'CGContextRestoreGState'功能相鄰的是什麼?您需要在更改狀態之前保存狀態,然後再恢復。 – Hamish
我是CGContext&UIGraphics的新手,我在這裏找到了這段代碼,但是不起作用。但是,感謝您的回覆 – ankmara
您似乎已經複製併合並了隨機代碼。你爲什麼使用'kCGBlendModeDarken'和'kCGBlendModeDarken'。你爲什麼設置和恢復圖形狀態?不要只複製你找到的代碼。你需要知道它做了什麼。這個問題並不難。這似乎很難,因爲你在做些隨意的事情。 –