iOS UI效果之毛玻璃效果和渐变效果
1.渐变效果
CAGradientLayer
CAGradientLayer继承于CALayer,
主要属性:
@property(nullable, copy) NSArray *colors;
/* An optional array of NSNumber objects defining the location of each
* gradient stop as a value in the range [0,1]. The values must be
* monotonically increasing. If a nil array is given, the stops are
* assumed to spread uniformly across the [0,1] range. When rendered,
* the colors are mapped to the output colorspace before being
* interpolated. Defaults to nil. Animatable. */
@property(nullable, copy) NSArray<NSNumber *> *locations;
/* The start and end points of the gradient when drawn into the layer's
* coordinate space. The start point corresponds to the first gradient
* stop, the end point to the last gradient stop. Both points are
* defined in a unit coordinate space that is then mapped to the
* layer's bounds rectangle when drawn. (I.e. [0,0] is the bottom-left
* corner of the layer, [1,1] is the top-right corner.) The default values
* are [.5,0] and [.5,1] respectively. Both are animatable. */
@property CGPoint startPoint;
@property CGPoint endPoint;
其中colors是几个关键点的颜色,locations是关键点的位置,locations的个数与colors对应,从0到1的范围,确定颜色的变化率;
startPoint和endPoint控制起点和结束点,比较直接的控制变化的方向。
下面贴一下代码
- (void)insertGradient {
UIColor *colorRed = [UIColor redColor];
UIColor *colorBlue = [UIColor blueColor];
UIColor *colorGreen = [UIColor greenColor];
NSArray *colors = [NSArray arrayWithObjects:(id)colorRed.CGColor, (id)colorBlue.CGColor, (id)colorGreen.CGColor, nil];
NSNumber *locationR = [NSNumber numberWithFloat:0.0];
NSNumber *locationB = [NSNumber numberWithFloat:0.35];
NSNumber *locationG = [NSNumber numberWithFloat:1.0];
NSArray *locations = [NSArray arrayWithObjects:locationR, locationB, locationG, nil];
//crate gradient layer
CAGradientLayer *headerLayer = [CAGradientLayer layer];
headerLayer.colors = colors;
headerLayer.locations = locations;
headerLayer.startPoint = CGPointMake(0.5, 0.);
headerLayer.endPoint = CGPointMake(1, 1);
headerLayer.frame = CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.width);
[self.view.layer addSublayer:headerLayer];
}
2.毛玻璃效果
UIVisualEffectView
UIVisualEffectView是iOS8为实现一些复杂UI效果新增的类。
主要属性:
@property (nonatomic, strong, readonly) UIView *contentView; // Do not add subviews directly to UIVisualEffectView, use this view instead.
@property (nonatomic, copy, nullable) UIVisualEffect *effect;
UIVisualEffect是创建视觉效果的基类,实现效果可以用它的两个子类UIBlurEffect和UIVibrancyEffect。
UIBlurEffect就是实现模糊效果的类。
使用比较简单,如下:
- (void)insertBlurView {
UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *blurView = [[UIVisualEffectView alloc] initWithEffect:effect];
blurView.frame = self.view.bounds;
[self.view addSubview:blurView];
}
这种方法不能控制模糊的程度,如果要控制模糊的程度,可以使用GPUImage。