iOS开发:UIImage赋颜色-----给image赋16进制颜色值

倪阳飇
2023-12-01

UIImage赋颜色:给image赋16进制颜色值

本讲:

    在今天的项目中遇到了一个问题:从网络段解析的数据中得到的image是透明的(白色的),看不到它,研究好久,发现数据解析里有一个16进制的颜色值。需要把这个颜色值赋给image。

问题:

<UIKit/UIKit.h>中并没有现成的直接给image赋值的方法。

办法:

1.写一个类目,把16进制的颜色值转化成10进制颜色值;
2.写一个类目,给image赋颜色值;

代码

颜色:16进制——>10进制

+ (UIColor *)RGBFromHexColor:(NSString *)hexadecimalColor
{
    NSString *colorString = [[hexadecimalColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    if ([colorString length] < 6) {
        return [UIColor clearColor];
    }

    //16进制,以“0X”开头
    if ([colorString hasPrefix:@"0X"])
        colorString = [colorString substringFromIndex:2];
    //16进制,以“#”开头
    if ([colorString hasPrefix:@"#"])
        colorString = [colorString substringFromIndex:1];

    if ([colorString length] != 6)
        return [UIColor clearColor];
    NSRange range;
     //前两个是r
    range.location = 0;
    range.length = 2;
    NSString *rString = [colorString substringWithRange:range];
    //中间两个是g
    range.location = 2;
    NSString *gString = [colorString substringWithRange:range];
    //最后两个是b
    range.location = 4;
    NSString *bString = [colorString substringWithRange:range];
    unsigned int r, g, b;
    //转码:
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

给image赋颜色

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

    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(contextRef, 0, self.size.height);
    CGContextScaleCTM(contextRef, 1.0, -1.0);
    CGContextSetBlendMode(contextRef, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextClipToMask(contextRef, rect, self.CGImage);
    [color setFill];
    CGContextFillRect(contextRef, rect);
    UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
 类似资料: