2016-07-27 6 views
0

私は最近、プログラムでインターフェイスを処理し始めました。画像を背景として設定してぼかしを施したいと思います。xboxにぼかし画像の背景をプログラムで追加する

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

を私が言ったように私はこれに新しい終了しています: は、私は次のようなサンプルコードを見てきました。どういうふうに説明できますか?どこで使うべきですか?

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

をしかし、これはパフォーマンス上の問題を引き起こすことがあります。

答えて

2

最も簡単なのは、ちょうどこのような視覚効果を追加します。そのため、最善の解決策は、イメージをぼかしで再描画し、ぼかしたイメージを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) 

は、オプションの値のケアが必要です。 (UIImageの拡張として追加)

+0

本であるObjective-Cの右? Swiftを使って同じことをどうやってやり遂げることができますか? :) –

+0

スイフトには同じAPIがあります。ちょうどそれを翻訳する。 – zylenv

0

スイフト3.1バージョン:

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) 
    } 

} 
関連する問題