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一一對應,而且,顏色的值是可以設置透明度的,這點相當重要哦.
附錄:
