UIColor转换以及简单扩展

UIColor转换以及简单扩展

概述

UIColor也是我们开发中必然会用到的内容,这里简单的归类了一些常用功能:

  • hexString转到UIColor
  • PatternImage获取UIColor
  • UIColor转换成图片

这里创建了分类UIColor+MMAddition.{h,m}来简单的总结上述几个点

文件代码UIColor+MMAddition.{h,m}下载直接使用

下面也是全部代码的介绍,可以Ctrl+C使用

API

1、+ (UIColor )colorWithHexString:(NSString )hexString

通过16进制hexString色值直接获取UIColor对象


+ (UIColor *)colorWithHexString:(NSString *)hexString {

    return [self colorWithHexString:hexString alpha:1.0f];
}

+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {

    NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    if ([cString length] < 6)
        return nil;
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return nil;

    NSString *rString = [cString substringWithRange:NSMakeRange(0, 2)];
    NSString *gString = [cString substringWithRange:NSMakeRange(2, 2)];
    NSString *bString = [cString substringWithRange:NSMakeRange(4, 2)];


    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    UIColor *hexColor = [UIColor colorWithRed:((float) r / 255.0f)
                                        green:((float) g / 255.0f)
                                         blue:((float) b / 255.0f)
                                        alpha:alpha];

    return hexColor;
}
2、+ (UIColor )colorWithUIImage:(UIImage )image

从一张纯色图获取颜色

+ (UIColor *)colorWithUIImage:(UIImage *)image {
    return [self colorWithPatternImage:image];
}

3、+ (UIImage )imageWithColor:(UIColor )color

UIColor颜色获取UIImage对象

+ (UIImage *)imageWithColor:(UIColor *)color {

    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return theImage;
}
4、+ (UIImage )imageWithHexString:(NSString )hexString

由16进制HexString颜色获取UIImage对象

+ (UIImage *)imageWithHexString:(NSString *)hexString {
    return [self imageWithColor:[self colorWithHexString:hexString]];
}

PS:以上部分代码需要配套使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值