如何为背景设置十六进制颜色代码 [英] how to set hex color code for background
本文介绍了如何为背景设置十六进制颜色代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
创建一个uicolor-from-a-hex-string>
我想以编程方式设置UIView背景的颜色。
似乎我不能通过Interfacebuilder 。我应该怎么做,如果我想将它设置为一些十六进制代码的颜色?
我喜欢用这个小小的一块代码在我的应用程序中使用HTML Web颜色。用法:
[self.view setBackgroundColor:[self colorWithHexString :@ FFFFFF]]; / *白色* /
代码:
- (UIColor *)colorWithHexString:(NSString *)hex
{
NSString * cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
//字符串应该是6或8个字符
if([cString length] <6)return [UIColor grayColor];
//如果它出现
,剥离0X if([cString hasPrefix:@0X])cString = [cString substringFromIndex:2];
if([cString length]!= 6)return [UIColor grayColor];
//分为r,g,b子串
NSRange范围;
range.location = 0;
range.length = 2;
NSString * rString = [cString substringWithRange:range];
range.location = 2;
NSString * gString = [cString substringWithRange:range];
range.location = 4;
NSString * bString = [cString substringWithRange:range];
//扫描值
unsigned int r,g,b;
[[NSScanner scannerWithString:rString] scanHexInt:& r];
[[NSScanner scannerWithString:gString] scanHexInt:& g];
[[NSScanner scannerWithString:bString] scanHexInt:& b];
$ b return [UIColor colorWithRed :((float)r / 255.0f)
green:((float)g / 255.0f)
blue:((float)b / 255.0 f)
alpha:1.0f];
}
Possible Duplicate:
How can I create a UIColor from a hex string?
I want to programmatically set the color of the UIView Background.
It doesn't seem like I can do it through Interfacebuilder. How should I do it if I want to set it to some hex code color?
解决方案
I like to use this little piece of code to use HTML web colors in my apps.
Usage:
[self.view setBackgroundColor: [self colorWithHexString:@"FFFFFF"]]; /* white */
The Code:
-(UIColor*)colorWithHexString:(NSString*)hex
{
NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) return [UIColor grayColor];
// strip 0X if it appears
if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
if ([cString length] != 6) return [UIColor grayColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
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];
}
这篇关于如何为背景设置十六进制颜色代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文