我尝试过drawInRect
,CGContextDrawImage
但它适用于整个图像.
我希望它仅适用于图像部分,而不是透明部分.有谁知道怎么做?
您可以使用UIImage
alpha通道作为绘图的蒙版.
- (UIImage *)overlayImage:(UIImage *)image withColor:(UIColor *)color { // Create rect to fit the PNG image CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height); // Start drawing UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); // Fill the rect by the final color [color setFill]; CGContextFillRect(context, rect); // Make the final shape by masking the drawn color with the images alpha values CGContextSetBlendMode(context, kCGBlendModeDestinationIn); [image drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1]; // Create new image from the context UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); // Release context UIGraphicsEndImageContext(); return img; }
用法示例:
UIImage *pngImage = [UIImage imageNamed:@"myImage"]; UIColor *overlayColor = [UIColor magentaColor]; UIImage *image = [self overlayImage:pngImage withColor:overlayColor];
extension UIImage { func overlayed(by overlayColor: UIColor) -> UIImage { // Create rect to fit the image let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) // Create image context. 0 means scale of device's main screen UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) let context = UIGraphicsGetCurrentContext()! // Fill the rect by the final color overlayColor.setFill() context.fill(rect) // Make the final shape by masking the drawn color with the images alpha values self.draw(in: rect, blendMode: .destinationIn, alpha: 1) // Create new image from the context let overlayedImage = UIGraphicsGetImageFromCurrentImageContext()! // Release context UIGraphicsEndImageContext() return overlayedImage } }
用法示例:
let overlayedImage = myImage.overlayed(by: .magenta)
编辑:正如Desdenova在评论中指出的那样,我误解了这个问题.我原来的答案是在彩色背景上绘制PNG.答案已编辑,下面的代码是原始代码.
- (UIImage *)combineImage:(UIImage *)image withBackgroundColor:(UIColor *)bgColor { // Create rect to fit the PNG image CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height); // Create bitmap contect UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); // Draw background first // Set background color (will be under the PNG) [bgColor setFill]; // Fill all context with background image CGContextFillRect(context, rect); // Draw the PNG over the background [image drawInRect:rect]; // Create new image from the context UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); // Release context UIGraphicsEndImageContext(); return img; }