首页 > 学院 > 开发设计 > 正文

CAGradientLayer的使用(渐变)

2019-11-09 15:02:43
字体:
来源:转载
供稿:网友

1.颜色渐变

-(void)createUI{ UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(10, 400, 350, 20)]; [self.view addSubview:myView]; // 创建 CAGradientLayer 对象 CAGradientLayer *gradientLayer = [CAGradientLayer layer]; // 设置 gradientLayer 的 Frame gradientLayer.frame = myView.bounds; // 设置渐变颜色方向,左上点为(0,0), 右下点为(1,1) gradientLayer.startPoint = CGPointMake(0, 0.5); gradientLayer.endPoint = CGPointMake(1.0, 0.5); // 创建渐变色数组,需要转换为CGColor颜色 NSMutableArray * colorsArray = [NSMutableArray array]; for (NSInteger i = 0; i <= 360; i += 5) { UIColor *color = [UIColor colorWithHue:1.0 * i / 360 saturation:1.0 brightness:1.0 alpha:1.0]; [colorsArray addObject:(id)[color CGColor]]; }; gradientLayer.colors = colorsArray; // 添加渐变色到创建的 UIView 上去 [myView.layer addSublayer:gradientLayer];}

这里写图片描述 2.图片显示

CAGradientLayer * gradientLayer = [[CAGradientLayer alloc] init]; gradientLayer.frame = self.baseImageView.bounds; gradientLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor,(__bridge id)[UIColor blackColor].CGColor,(__bridge id)[UIColor clearColor].CGColor]; gradientLayer.locations = @[@(0.25),@(0.5),@(0.75)]; gradientLayer.startPoint = CGPointMake(0, 0); gradientLayer.endPoint = CGPointMake(1, 1);// 创建一个接受 gradientLayer 的 View _containtView = [[UIView alloc] initWithFrame:_baseImageView.bounds]; [_containtView.layer addSublayer:gradientLayer];// 将 _baseImageView 的 maskView 设置为 containtView self.baseImageView.maskView = _containtView; [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(repeat) userInfo:nil repeats:YES];

定时器

- (void)repeat{ dispatch_async(dispatch_get_main_queue(), ^{ __block CGRect rect = CGRectMake(-_baseImageView.bounds.size.width, 0, _baseImageView.bounds.size.width * 2, _baseImageView.bounds.size.height * 2); _containtView.frame = rect; [UIView animateWithDuration:1.0f animations:^{ rect.origin.x = _baseImageView.bounds.size.width; _containtView.frame = rect; }]; });}

效果图


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表