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)室從左下角向右上角漸變。

 

總之,靈活運用,要是想了解更多,就自己好好研究哈。

 


免責聲明!

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



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