Wilson Tang’s Blog

I am a slow walker, but I never walk backwards.

UIView的模糊效果

| Comments

效果图

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import UIKit

class ViewController: UIViewController {

    var effectView : UIVisualEffectView!
    var mySegcon : UISegmentedControl!

    override func viewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor = UIColor.cyanColor()

        let image = UIImage(named: "test")
        let imageView = UIImageView(frame: self.view.bounds)
        imageView.image = image

        self.view.addSubview(imageView)

        mySegcon = UISegmentedControl(items: ["Dark", "ExtraLight", "Light"])
        mySegcon.center = CGPointMake(self.view.center.x, self.view.bounds.maxY - 50)
        mySegcon.backgroundColor = UIColor.grayColor()
        mySegcon.tintColor = UIColor.whiteColor()

        mySegcon.addTarget(self, action: "onClickMySegmentedControl:", forControlEvents: UIControlEvents.ValueChanged)
        self.view.addSubview(mySegcon)
    }

    func addVirtualEffectView(effect : UIBlurEffect!){
        if effectView != nil {
            effectView.removeFromSuperview()
        }
        effectView = UIVisualEffectView(effect: effect)
        effectView.frame = CGRectMake(0, 0, 200, 400)
        effectView.layer.position = CGPointMake(mySegcon.bounds.midX, -(effectView.frame.midY + 20) )
        effectView.layer.masksToBounds = true
        effectView.layer.cornerRadius = 20.0
        mySegcon.addSubview(effectView)
    }

    func onClickMySegmentedControl(sender : UISegmentedControl){
        var effect : UIBlurEffect!
        switch(sender.selectedSegmentIndex){
        case 0:
            effect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        case 1:
            effect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        case 2:
            effect = UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)
        default:
            println("Error")
        }
        self.addVirtualEffectView(effect)
    }
}

Comments