模糊前
模糊后
extension UIView {
//高斯模糊
func blurEffect(){
let blur = UIBlurEffect(style: .light)
let effectView = UIVisualEffectView(effect: blur)
effectView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
addSubview(effectView)
}
}
使用
imageView.blurEffect()
2.oc
2.1 代码运行后的效果图
2.2 代码
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageview = [[UIImageView alloc] init];
imageview.frame = CGRectMake(10, 100, 300, 300);
imageview.image = [UIImage imageNamed:@"img"];
imageview.contentMode = UIViewContentModeScaleAspectFit;
imageview.userInteractionEnabled = YES;
[self.view addSubview:imageview];
UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
effectview.frame = CGRectMake(0, 0, imageview.frame.size.width/2, 300);
[imageview addSubview:effectview];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
btn.frame = CGRectMake(10, 50, 100, 40);
[btn setTitle:@"btn" forState:UIControlStateNormal];
[effectview.contentView addSubview:btn];
}
参考博客
iOS高斯模糊实现
其他:我朋友的代码DispatchQueue.global().async {[weak self] in
let size = CGSize.init(width: MKScreenU.width, height: (self?.headerImageViewDefaultHeight)!)
guard let image = img else { return }
let scaleDownSize = CGSize.init(width: image.size.width / 10.0, height: image.size.height / 10.0)
guard let originalImage = image.sd_resizedImage(with: scaleDownSize, scaleMode: .aspectFill) else { return }
UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale)
// 高斯模糊
let gimage2 = originalImage.qh_applyGaussianBlurFilter(val: 5)
let scaleValue = image.size.width / size.width
gimage2?.draw(in: CGRect.init(x: 0, y: (size.height - (image.size.height / scaleValue)) / 2.0, width: size.width, height: image.size.height / scaleValue))
// 黑色遮罩
let path = UIBezierPath.init(rect: CGRect.init(origin: .zero, size: size))
UIColor.black.withAlphaComponent(0.4).setFill()
path.fill()
let resultImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
SDImageCache.shared.store(resultImage, forKey: cacheKey) {
}
DispatchQueue.main.async {
self?.headerImageView.image = resultImage
}
}
func qh_applyGaussianBlurFilter(val: CGFloat) -> UIImage? {
guard let aCIImage = CIImage.init(image: self) else { return nil }
let clampFilter = CIFilter(name: "CIAffineClamp")
clampFilter?.setDefaults()
clampFilter?.setValue(aCIImage, forKey: kCIInputImageKey)
let blurFilter = CIFilter(name: "CIGaussianBlur")
blurFilter?.setValue(clampFilter?.outputImage, forKey: kCIInputImageKey)
blurFilter?.setValue(val, forKey: kCIInputRadiusKey)
let rect = aCIImage.extent
if let output = blurFilter?.outputImage {
let context = CIContext(options: nil)
if let cgimg = context.createCGImage(output, from: rect) {
let processedImage = UIImage(cgImage: cgimg)
return processedImage
}
}
fatalError()
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)