CAGradientLayer

用于处理渐变色的层结构

大部分情况下,CAGradientLayer时和CAShapeLayer配合使用的

CAGradientLayer可以用作PNG的遮罩效果

渐变样式属性

四个属性 colors locations startPoint endPoint 都是可以进行动画

  • @property(copy) NSArray *colors
    • 对象数组定义每个梯度停止的颜色。
  • @property(copy) NSArray <NSNumber *> *locations
    • 可选NSNumber数组定义每个梯度停止的位置
    • 值的范围为0~1、且数组中的值必须是递增的
    • locations并不是表示颜色值所在位置,它表示的是颜色在Layer坐标系相对位置处要开始进行渐变颜色了
  • @property CGPoint startPoint 、 @property CGPoint endPoint
    • 渐变色的方向就会根据起点指向终点的方向来渐变
    • 默认值分别为:(0.5,0.0)、(0.5,1.0)

坐标系统

渐变色的作用范围,变化梯度的方向,颜色变换的作用点都和CAGradientLayer的坐标系统有关

  1. CAGradientLayer的坐标系统是从(0,0)到(1,1)绘制的矩形
  2. CAGradientLayer的frame值的size不为正方形的话,坐标系统会被拉伸
  3. CAGradientLayer的startPoint和endPoint会直接决定颜色的绘制方向
  4. CAGradientLayer的颜色分割点时以0到1的比例来计算的

如图:

示例代码

#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) CAGradientLayer *gradientLayer;
@property (strong, nonatomic) NSTimer *timer;
@end
...
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
 
//初始化imageView
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image"]];
imageView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 200);
imageView.center = self.view.center;
[self.view addSubview:imageView];
 
//初始化渐变层
self.gradientLayer = [CAGradientLayer layer];
self.gradientLayer.frame = imageView.bounds;
[imageView.layer addSublayer:self.gradientLayer];
 
//设置渐变颜色方向
self.gradientLayer.startPoint = CGPointMake(0, 0);
self.gradientLayer.endPoint = CGPointMake(0, 1);
 
//设定颜色组
self.gradientLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor,
                              (__bridge id)[UIColor purpleColor].CGColor];
 
//设定颜色分割点
self.gradientLayer.locations = @[@(0.5f) ,@(1.0f)];
 
//定时器
self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0f
                                              target:self
                                            selector:@selector(TimerEvent)
                                            userInfo:nil
                                             repeats:YES];
}
-(void)TimerEvent
{
    //定时改变颜色
    self.gradientLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor,
                              (__bridge id)[UIColor colorWithRed:arc4random() % 255 / 255.0
                                                           green:arc4random() % 255 / 255.0
                                                            blue:arc4random() % 255 / 255.0
                                                           alpha:1.0].CGColor];
 
//定时改变分割点
self.gradientLayer.locations = @[@(arc4random() % 10 / 10.0f), @(1.0f)];
}
@end

如图:

posted @ 2016-04-06 15:41  孙焱焱  阅读(2877)  评论(0编辑  收藏  举报