IOS 实现颜色渐变扩展

2019-01-23  本文已影响0人  迷雾前行

//绘制渐变色颜色的方法

+ (CAGradientLayer*)setGradualChangingColor:(UIView*)view fromColor:(NSString*)fromHexColorStr toColor:(NSString*)toHexColorStr{

    //    CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角)

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];

    gradientLayer.frame= view.bounds;

    //  创建渐变色数组,需要转换为CGColor颜色

    gradientLayer.colors=@[(__bridgeid)[UIColorcolorWithHex:fromHexColorStr].CGColor,(__bridgeid)[UIColorcolorWithHex:toHexColorStr].CGColor];

    //  设置渐变颜色方向,左上点为(0,0), 右下点为(1,1)

    gradientLayer.startPoint=CGPointMake(0,0);

    gradientLayer.endPoint=CGPointMake(1,1);

    //  设置颜色变化点,取值范围 0.0~1.0

    gradientLayer.locations=@[@0,@1];

    return gradientLayer;

}

//获取16进制颜色的方法

+ (UIColor*)colorWithHex:(NSString*)hexColor {

    hexColor = [hexColorstringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    if([hexColorlength] <6) {

        returnnil;

    }

    if([hexColorhasPrefix:@"#"]) {

        hexColor = [hexColorsubstringFromIndex:1];

    }

    NSRangerange;

    range.length=2;

    range.location=0;

    NSString*rs = [hexColorsubstringWithRange:range];

    range.location=2;

    NSString*gs = [hexColorsubstringWithRange:range];

    range.location=4;

    NSString*bs = [hexColorsubstringWithRange:range];

    unsignedintr, g, b, a;

    [[NSScanner scannerWithString:rs] scanHexInt:&r];

    [[NSScanner scannerWithString:gs] scanHexInt:&g];

    [[NSScanner scannerWithString:bs] scanHexInt:&b];

    if([hexColorlength] ==8) {

        range.location=4;

        NSString*as = [hexColorsubstringWithRange:range];

        [[NSScanner scannerWithString:as] scanHexInt:&a];

    }else{

        a =255;

    }

    return[UIColorcolorWithRed:((float)r /255.0f)green:((float)g /255.0f)blue:((float)b /255.0f)alpha:((float)a /255.0f)];

}

//方法使用

    UIView*sysView = [UIViewnew];

    [sysViewsetFrame:CGRectMake(60,60,100,40)];

    sysView.layer.cornerRadius = 20.0;

    sysView.layer.masksToBounds = YES;

    [sysView.layer addSublayer:[UIColor setGradualChangingColor:sysView fromColor:@"F76B1C" toColor:@"FBDA61"]];

    [self.viewaddSubview:sysView];

上一篇 下一篇

猜你喜欢

热点阅读