2016-07-27 178 views
0

我最近开始以编程方式处理我的界面,并且想要将图像设置为我的故事板的背景,然后使其模糊。 我见过的示例代码如下所示:以编程方式将模糊图像背景添加到xib

UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Wormhole.jpg"]]; 
[self.view insertSubview:backgroundView atIndex:0]; 

但正如我所说,我不干新本。有人可以解释它是如何工作的吗?我应该在哪里使用它?

回答

2

最简单的,只需要加一个视觉效果是这样的:

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]; 

雨燕代码:

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) 

要小心选购价值。

+0

这是目标c正确?我怎么能通过Swift做同样的事情? :) –

+0

Swift具有相同的API。只需翻译它。 – zylenv

0

夫特版本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) 
    } 

}