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一一对应,而且,颜色的值是可以设置透明度的,这点相当重要哦.
附录:
CAGradientLayer实现图片渐变透明效果,布布扣,bubuko.com