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

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM