首页 > 代码库 > iOS 设置字体为渐变色

iOS 设置字体为渐变色

方法类

#import "Healp.h"

@implementation Healp

/*
 view 是要设置渐变字体的控件   bgVIew是view的父视图  colors是渐变的组成颜色  startPoint是渐变开始点 endPoint结束点
 */
+(void)TextGradientview:(UIView *)view bgVIew:(UIView *)bgVIew gradientColors:(NSArray *)colors gradientStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint{
    
    CAGradientLayer* gradientLayer1 = [CAGradientLayer layer];
    gradientLayer1.frame = view.frame;
    gradientLayer1.colors = colors;
    gradientLayer1.startPoint =startPoint;
    gradientLayer1.endPoint = endPoint;
    [bgVIew.layer addSublayer:gradientLayer1];
    gradientLayer1.mask = view.layer;
    view.frame = gradientLayer1.bounds;
}

/*
 control 是要设置渐变字体的控件   bgVIew是control的父视图  colors是渐变的组成颜色  startPoint是渐变开始点 endPoint结束点
 */
+(void)TextGradientControl:(UIControl *)control bgVIew:(UIView *)bgVIew gradientColors:(NSArray *)colors gradientStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint{

    CAGradientLayer* gradientLayer1 = [CAGradientLayer layer];
    gradientLayer1.frame = control.frame;
    gradientLayer1.colors = colors;
    gradientLayer1.startPoint =startPoint;
    gradientLayer1.endPoint = endPoint;
    [bgVIew.layer addSublayer:gradientLayer1];
    gradientLayer1.mask = control.layer;
    control.frame = gradientLayer1.bounds;
}

引用

 
    /*方法1*/
    
    UILabel* testLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 200, 400, 50)];
    testLabel.text = @"label上渐变方法1";
    testLabel.font = [UIFont systemFontOfSize:30];
    [self.view addSubview:testLabel];
    [Healp TextGradientview:testLabel bgVIew:self.view gradientColors:@[(id)[UIColor redColor].CGColor, (id)[UIColor greenColor].CGColor, (id)[UIColor blueColor].CGColor] gradientStartPoint:CGPointMake(0, 1) endPoint:CGPointMake(1, 1)];
    

    /*方法2*/
    _label=[[UILabel alloc]initWithFrame:CGRectMake(10, 300, self.view.frame.size.width-20,50)];
    [self.view addSubview:_label];
    _label.text=@"label上渐变方法2";
    _label.textAlignment=NSTextAlignmentCenter;
    _label.font = [UIFont systemFontOfSize:30];
    _label.textColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"gradient"]];
    

    
    _btn=[[UIButton alloc]initWithFrame:CGRectMake(10, 350, self.view.frame.size.width-20, 100)];
    [self.view addSubview:_btn];
    _btn.titleLabel.font=[UIFont systemFontOfSize:30];
    _btn.titleLabel.numberOfLines=0;
    [_btn setTitle:@"button上字体渐变色设置" forState:UIControlStateNormal];
    [Healp TextGradientControl:_btn bgVIew:self.view gradientColors:@[(id)[UIColor redColor].CGColor, (id)[UIColor greenColor].CGColor, (id)[UIColor blueColor].CGColor] gradientStartPoint:CGPointMake(0, 1) endPoint:CGPointMake(1, 1)];
    

 

iOS 设置字体为渐变色