首页 > 代码库 > CAGradientLayer实现图片渐变透明效果
CAGradientLayer实现图片渐变透明效果
CAGradientLayer实现图片渐变透明效果
要实现的效果如下:
源码:
// // RootViewController.m // CAGradientLayer // // Copyright (c) 2014年 Y.X. All rights reserved. // #import "RootViewController.h" #import "YXGCD.h" @interface RootViewController () @property (nonatomic, strong) GCDTimer *timer; @end @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor redColor]; // 背景图片 UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds]; imageView.image = [UIImage imageNamed:@"猫"]; [self.view addSubview:imageView]; UIView *yourGradientView = [[UIView alloc] initWithFrame:self.view.bounds]; // 渐变图层 CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.frame = yourGradientView.bounds; // 设置颜色 gradientLayer.colors = @[(id)[[UIColor clearColor] colorWithAlphaComponent:0.0f].CGColor, (id)[[UIColor redColor] colorWithAlphaComponent:1.0f].CGColor]; gradientLayer.locations = @[[NSNumber numberWithFloat:0.7f], [NSNumber numberWithFloat:1.0f]]; // 添加渐变图层 [yourGradientView.layer addSublayer:gradientLayer]; [self.view addSubview:yourGradientView]; // 开始动画效果 _timer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]]; [_timer event:^{ gradientLayer.locations = @[[NSNumber numberWithFloat:arc4random()%100/100.f], [NSNumber numberWithFloat:1.0f]]; gradientLayer.colors = @[(id)[[UIColor clearColor] colorWithAlphaComponent:0.0f].CGColor, (id)[[UIColor colorWithRed:arc4random()%255/255.f green:arc4random()%255/255.f blue:arc4random()%255/255.f alpha:1.0] colorWithAlphaComponent:1.0f].CGColor]; } timeInterval:NSEC_PER_SEC]; [_timer start]; } @end
效果如下:
核心的地方:
colors与locations一一对应,而且,颜色的值是可以设置透明度的,这点相当重要哦.
附录:
http://stackoverflow.com/questions/22755016/how-to-achieve-this-effect-in-iphone-sdk/22755078#22755078
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。