iOS:创buildUIImage的较暗版本并保持透明像素不变?
我发现
通过向现有的UIImage添加阴影来创build新的UIImage
和
UIImage,有没有一种简单的方法来使它更黑或全黑
但选定的答案不适合我。
我有一个UIImage,它可能有一些透明的像素,我需要创build一个新的UIImage与不透明的像素变暗,有没有办法做到这一点? 我正在考虑使用UIBezierPath,但我不知道如何做只为非透明的像素。
即使它们是透明的,这也是我用来给图像上色的类。
+ (UIImage *)colorizeImage:(UIImage *)image withColor:(UIColor *)color { UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale); CGContextRef context = UIGraphicsGetCurrentContext(); CGRect area = CGRectMake(0, 0, image.size.width, image.size.height); CGContextScaleCTM(context, 1, -1); CGContextTranslateCTM(context, 0, -area.size.height); CGContextSaveGState(context); CGContextClipToMask(context, area, image.CGImage); [color set]; CGContextFillRect(context, area); CGContextRestoreGState(context); CGContextSetBlendMode(context, kCGBlendModeMultiply); CGContextDrawImage(context, area, image.CGImage); UIImage *colorizedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return colorizedImage; }
要使图像变暗,您需要将透明度较低的黑色或灰色UIColor传递给方法。
如何尝试一个CoreImage筛选器?
您可以使用CIColorControlsfilter来调整input亮度和对比度以使图像变暗。
CIContext *context = [CIContext contextWithOptions:nil]; CIImage *inputImage = [[CIImage alloc] initWithImage:sourceImage]; //your input image CIFilter *filter= [CIFilter filterWithName:@"CIColorControls"]; [filter setValue:inputImage forKey:@"inputImage"]; [filter setValue:[NSNumber numberWithFloat:0.5] forKey:@"inputBrightness"]; // Your output image UIImage *outputImage = [UIImage imageWithCGImage:[context createCGImage:filter.outputImage fromRect:filter.outputImage.extent]];
阅读更多关于CIFilter参数的信息:
这是一个快速的Swift版本,使用CIExposureAdjust CIFilter 🙂
// Get the original image and set up the CIExposureAdjust filter guard let originalImage = UIImage(named: "myImage"), let inputImage = CIImage(image: originalImage), let filter = CIFilter(name: "CIExposureAdjust") else { return } // The inputEV value on the CIFilter adjusts exposure (negative values darken, positive values brighten) filter.setValue(inputImage, forKey: "inputImage") filter.setValue(-2.0, forKey: "inputEV") // Break early if the filter was not a success (.outputImage is optional in Swift) guard let filteredImage = filter.outputImage else { return } let context = CIContext(options: nil) let outputImage = UIImage(CGImage: context.createCGImage(filteredImage, fromRect: filteredImage.extent)) myImageView.image = outputImage // use the filtered UIImage as required.