我最近开始以编程方式处理我的界面,我想将图像设置为我的故事板的背景,然后使其模糊。 我见过以下示例代码:
UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Wormhole.jpg"]];
[self.view insertSubview:backgroundView atIndex:0];
但正如我所说,我已经不再采用此方法了。有人可以解释它是如何工作的吗?我应该在哪里使用它?
答案 0 :(得分:3)
最简单,只需添加如下视觉效果:
UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Wormhole.jpg"]];
[self.view insertSubview:backgroundView atIndex:0];
UIVisualEffectView *effect = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
[backgroundView addSubview:effect];
但这可能会导致性能问题。因此,最佳解决方案应该是您使用模糊重绘图像,并将模糊图像设置为backgroundView的图像。 如何模糊图像,请参阅below:
UIImageView *backgroundView = [[UIImageView alloc] init];
[self.view insertSubview:backgroundView atIndex:0];
UIImage *image = [UIImage imageNamed:@"Wormhole.jpg"];
//create blurred image
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
//setting up Gaussian Blur (we could use one of many filters offered by Core Image)
CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
[filter setValue:inputImage forKey:kCIInputImageKey];
[filter setValue:[NSNumber numberWithFloat:15.0f] forKey:@"inputRadius"];
CIImage *result = [filter valueForKey:kCIOutputImageKey];
CGImageRef cgImage = [context createCGImage:result fromRect:[inputImage extent]];
//add our blurred image
backgroundView.image = [UIImage imageWithCGImage:cgImage];
Swift代码:
let backgroundView = UIImageView()
self.view.addSubview(backgroundView)
let image = UIImage(named: "Wormhole.jpg")
let context = CIContext(options: nil)
let inputImage = CIImage(CGImage: image!.CGImage!)
let filter = CIFilter(name: "CIGaussianBlur")
filter!.setValue(inputImage, forKey: kCIInputImageKey)
filter!.setValue(15, forKey: "inputRadius")
let result = filter!.valueForKey(kCIOutputImageKey) as? CIImage
let cgImage = context.createCGImage(result!, fromRect: inputImage.extent)
backgroundView.image = UIImage(CGImage: cgImage)
注意可选值。
答案 1 :(得分:1)
Swift 3.1版本(作为UIImage的扩展添加):
extension UIImage {
func blurred(withRadius radius: Int) -> UIImage {
let context = CIContext(options: nil)
let inputImage = CIImage(cgImage: self.cgImage!)
let filter = CIFilter(name: "CIGaussianBlur")!
filter.setValue(inputImage, forKey: kCIInputImageKey)
filter.setValue(radius, forKey: "inputRadius")
let result = filter.value(forKey: kCIOutputImageKey) as! CIImage
let cgImage = context.createCGImage(result, from: inputImage.extent)!
return UIImage(cgImage: cgImage)
}
}