美文网首页iOS接下来要研究的知识点
iOS通过Category实现UIView渐变的背景颜色

iOS通过Category实现UIView渐变的背景颜色

作者: 德坤柳 | 来源:发表于2018-07-12 15:21 被阅读0次

    项目中有很多View和Button需要设置渐变的背景颜色,所以写了一个Category来方便调用。

    - (void)setGradientBackgroundColor
    {
        //创建一个渐变的图层
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor, (__bridge id)[UIColor blueColor].CGColor];
        gradientLayer.locations = @[@0, @1.0];
        gradientLayer.startPoint = CGPointMake(0, 0);
        gradientLayer.endPoint = CGPointMake(1.0, 0);
        gradientLayer.frame = self.bounds;
        gradientLayer.name = @"gradientLayer";
        
        //生成一个image
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);
        [gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        //设置背景颜色
        self.backgroundColor = [UIColor colorWithPatternImage:img];
    }
    

    调用方式,import这个category,在需要设置背景颜色的时候调用就可以了

    #import "UIView+Gradient.h"
    @interface ViewController ()
    @property (nonatomic, strong)UIView *tempView;
    @property (nonatomic, strong)UIView *childView;
    @end
    
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        _tempView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
        [self.view addSubview:_tempView];
        
        _childView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
        _childView.backgroundColor = [UIColor whiteColor];
        [_tempView addSubview:_childView];
        
        [_tempView setGradientBackgroundColor];
    }
    @end
    

    效果图


    渐变效果图.png

    参考链接
    ios实现颜色渐变的几种方法

    相关文章

      网友评论

        本文标题:iOS通过Category实现UIView渐变的背景颜色

        本文链接:https://www.haomeiwen.com/subject/iacrpftx.html