2016-07-27 137 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) 
    } 

}