我已经搜索了很多,但是如果您按下按钮,我找不到如何使 UIImageView 变暗...
我已经尝试使用过滤器等,但它不起作用。
那么我该怎么做呢?
不完美但相当不错:
public extension UIImage {
private enum BlendMode {
case multiply // This results in colors that are at least as dark as either of the two contributing sample colors
case screen // This results in colors that are at least as light as either of the two contributing sample colors
}
// A level of zero yeilds the original image, a level of 1 results in black
func darken(level: CGFloat = 0.5) -> UIImage? {
return blend(mode: .multiply, level: level)
}
// A level of zero yeilds the original image, a level of 1 results in white
func lighten(level: CGFloat = 0.5) -> UIImage? {
return blend(mode: .screen, level: level)
}
private func blend(mode: BlendMode, level: CGFloat) -> UIImage? {
let context = CIContext(options: nil)
var level = level
if level < 0 { level = 0 }
else if level > 1 { level = 1 }
let filterName: String
switch mode {
case .multiply: // As the level increases we get less white
level = abs(level - 1.0)
filterName = "CIMultiplyBlendMode"
case .screen: // As the level increases we get more white
filterName = "CIScreenBlendMode"
}
let blender = CIFilter(name: filterName)!
let backgroundColor = CIColor(color: UIColor(white: level, alpha: 1))
guard let inputImage = CIImage(image: self) else { return nil }
blender.setValue(inputImage, forKey: kCIInputImageKey)
guard let backgroundImageGenerator = CIFilter(name: "CIConstantColorGenerator") else { return nil }
backgroundImageGenerator.setValue(backgroundColor, forKey: kCIInputColorKey)
guard let backgroundImage = backgroundImageGenerator.outputImage?.cropped(to: CGRect(origin: CGPoint.zero, size: self.size)) else { return nil }
blender.setValue(backgroundImage, forKey: kCIInputBackgroundImageKey)
guard let blendedImage = blender.outputImage else { return nil }
guard let cgImage = context.createCGImage(blendedImage, from: blendedImage.extent) else { return nil }
return UIImage(cgImage: cgImage)
}
}
您可以在 imageView 中添加 CAGradientLayer。将以下代码添加到按钮按下事件中。
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.imageView.bounds
gradientLayer.colors = [UIColor.clearColor().CGColor,UIColor.blackColor().CGColor]
self.imageView.layer.addSublayer(gradientLayer)
Swift 5 的更新答案:
func addGradientOverlay() {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.imageView.bounds
gradientLayer.colors = [UIColor.clear.cgColor,UIColor.black.cgColor]
self.imageView.layer.addSublayer(gradientLayer)
}
对于一个非常简单但愚蠢的方法,我建议您创建一个具有黑色背景颜色的新 UIView,将其 alpha 设置为 0.5 或更低,将其框架设置为您的 UIImageView.frame 并将其放在上面:
UIView *tmpView = [[UIView alloc] initWithFrame:myImageView.frame.size.height];
tmpView.backgroundColor = [UIColor blackColor];
tmpView.alpha = 0.5
//add it on button press
[myImageView addSubview:tmpView];
虽然我不建议这样做,但它可能比所有那些 GPUImage 过滤器更容易掌握