zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    C/C++程序内存泄漏检测
    linux下的内存管理
    Linker Script 链接器脚本
    linux内核进程调度以及定时器实现机制
    嵌入式软件设计中查找缺陷的几个技巧
    winCE DEBUGZONE
    程序员三个境界
    EJB初识(通熟易懂)
    JVM/JDK/JRE/IDE—区别(很经典)
    dubbo初识(一)Dubbo架构设计详解
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/3754985.html
Copyright © 2011-2022 走看看