zoukankan      html  css  js  c++  java
  • iOS开发之创建颜色渐变视图View

      在iOS开发中有时需要自己自定义一个视图view的背景,而网上有人提出的在循环中不断alloc的方法设置其背景色渐变,会耗费很多内存和资源,极其不明智,而在CALayer中早就提供有图层渐变的类和相应的方法,有需要的可以仔细研究一下,这里给一个小示例,给各位参考一下。

      这里的方法是,

      1.建一个storyboard的工程;

      2.使用storyboard拖一个View到控制器视图上,并设置外部接口用于调用;

      3.进入到ViewControler.m中,敲入代码:

    #import "ViewController.h" 

    @interface ViewController ()

    @property (strong, nonatomic) IBOutlet UIView *colorBackgroundView;

    @end

    @implementation ViewController

    - (void)viewDidLoad {

        [super viewDidLoad];

        // Do any additional setup after loading the view, typically from a nib.

        

        self.colorBackgroundView.frame = CGRectMake(20, 70, CGRectGetWidth(self.view.frame)-2*20, 50);

        [self.view addSubview:self.colorBackgroundView];

        

        CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];

        gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,(__bridge id)[UIColor blueColor].CGColor];

        gradientLayer.startPoint = CGPointMake(0, 1);

        gradientLayer.endPoint = CGPointMake(1, 1);

        gradientLayer.frame = CGRectMake(0, 0, CGRectGetWidth(self.colorBackgroundView.frame), CGRectGetHeight(self.colorBackgroundView.frame));

        [self.colorBackgroundView.layer addSublayer:gradientLayer];

    }

      显示的结果为:

        

    如果将其中的两行代码修改一下,结果又会不一样,如下:

    1. 

      gradientLayer.startPoint = CGPointMake(0, 0);

        gradientLayer.endPoint = CGPointMake(1, 0);

    2.

    gradientLayer.startPoint = CGPointMake(0, 0);

        gradientLayer.endPoint = CGPointMake(1, 1);

    结果为

    3.

    gradientLayer.startPoint = CGPointMake(0, 1);

        gradientLayer.endPoint = CGPointMake(1, 1);

    结果为

    给位应该看出规律了吧,四种组合方式得到三种结果,

    (0,0)到(1,0)和(0,1)到(1,1)都是水平从左向右渐变;

    (0,0)到(1,1)是从左上角向右下角渐变;

    (0,1)到(1,0)室从左下角向右上角渐变。

    总之,灵活运用,要是想了解更多,就自己好好研究哈。

  • 相关阅读:
    Servlet & JSP
    Servlet & JSP
    Servlet & JSP
    Servlet & JSP
    Servlet & JSP
    Servlet & JSP
    Table of Contents
    Commons Codec
    14.Longest Common Prefix
    628.Maximum Product of Three Numbers
  • 原文地址:https://www.cnblogs.com/xingxingLove/p/4958460.html
Copyright © 2011-2022 走看看