我如何从十六进制字符串格式创建一个UIColor,如#00FF00?
当前回答
这是一个接受十六进制字符串并返回UIColor的函数。 (你可以输入十六进制字符串格式:#ffffff或ffffff)
用法:
var color1 = hexStringToUIColor("#d3d3d3")
斯威夫特4:
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
斯威夫特3:
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.characters.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
斯威夫特2:
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString
if (cString.hasPrefix("#")) {
cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
}
if ((cString.characters.count) != 6) {
return UIColor.grayColor()
}
var rgbValue:UInt32 = 0
NSScanner(string: cString).scanHexInt(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
沙德源代码:/ gist: de147c42d7b3063ef7bc
其他回答
上面的几个解决方案涉及到一些不必要的nsstring使用。这个UIColor类扩展更简单更快:
+ colorWithHex:(UInt32)hex alpha:(CGFloat)alpha
{
return [UIColor colorWithRed:((hex & 0xFF0000) >> 16)/255.0
green:((hex & 0x00FF00) >> 8)/255.0
blue:( hex & 0x0000FF)/255.0
alpha:alpha];
}
简单来说:
return [UIColor colorWithHex:0x006400 alpha:1.0]; // HTML darkgreen
我已经找到了一个与Android使用的十六进制格式字符串100%兼容的解决方案,我发现这在进行跨平台移动开发时非常有用。它让我在两个平台上都使用一种颜色。您可以在没有归属的情况下随意重用,如果您愿意,也可以在Apache许可下重用。
#import "UIColor+HexString.h"
@interface UIColor(HexString)
+ (UIColor *) colorWithHexString: (NSString *) hexString;
+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length;
@end
@implementation UIColor(HexString)
+ (UIColor *) colorWithHexString: (NSString *) hexString {
NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];
CGFloat alpha, red, blue, green;
switch ([colorString length]) {
case 3: // #RGB
alpha = 1.0f;
red = [self colorComponentFrom: colorString start: 0 length: 1];
green = [self colorComponentFrom: colorString start: 1 length: 1];
blue = [self colorComponentFrom: colorString start: 2 length: 1];
break;
case 4: // #ARGB
alpha = [self colorComponentFrom: colorString start: 0 length: 1];
red = [self colorComponentFrom: colorString start: 1 length: 1];
green = [self colorComponentFrom: colorString start: 2 length: 1];
blue = [self colorComponentFrom: colorString start: 3 length: 1];
break;
case 6: // #RRGGBB
alpha = 1.0f;
red = [self colorComponentFrom: colorString start: 0 length: 2];
green = [self colorComponentFrom: colorString start: 2 length: 2];
blue = [self colorComponentFrom: colorString start: 4 length: 2];
break;
case 8: // #AARRGGBB
alpha = [self colorComponentFrom: colorString start: 0 length: 2];
red = [self colorComponentFrom: colorString start: 2 length: 2];
green = [self colorComponentFrom: colorString start: 4 length: 2];
blue = [self colorComponentFrom: colorString start: 6 length: 2];
break;
default:
[NSException raise:@"Invalid color value" format: @"Color value %@ is invalid. It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hexString];
break;
}
return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}
+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {
NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
unsigned hexComponent;
[[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
return hexComponent / 255.0;
}
@end
迅速:
extension UIColor {
convenience init?(hexString: String?) {
let input: String! = (hexString ?? "")
.replacingOccurrences(of: "#", with: "")
.uppercased()
var alpha: CGFloat = 1.0
var red: CGFloat = 0
var blue: CGFloat = 0
var green: CGFloat = 0
switch (input.count) {
case 3 /* #RGB */:
red = Self.colorComponent(from: input, start: 0, length: 1)
green = Self.colorComponent(from: input, start: 1, length: 1)
blue = Self.colorComponent(from: input, start: 2, length: 1)
break
case 4 /* #ARGB */:
alpha = Self.colorComponent(from: input, start: 0, length: 1)
red = Self.colorComponent(from: input, start: 1, length: 1)
green = Self.colorComponent(from: input, start: 2, length: 1)
blue = Self.colorComponent(from: input, start: 3, length: 1)
break
case 6 /* #RRGGBB */:
red = Self.colorComponent(from: input, start: 0, length: 2)
green = Self.colorComponent(from: input, start: 2, length: 2)
blue = Self.colorComponent(from: input, start: 4, length: 2)
break
case 8 /* #AARRGGBB */:
alpha = Self.colorComponent(from: input, start: 0, length: 2)
red = Self.colorComponent(from: input, start: 2, length: 2)
green = Self.colorComponent(from: input, start: 4, length: 2)
blue = Self.colorComponent(from: input, start: 6, length: 2)
break
default:
NSException.raise(NSExceptionName("Invalid color value"), format: "Color value \"%@\" is invalid. It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", arguments:getVaList([hexString ?? ""]))
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
static func colorComponent(from string: String!, start: Int, length: Int) -> CGFloat {
let substring = (string as NSString)
.substring(with: NSRange(location: start, length: length))
let fullHex = length == 2 ? substring : "\(substring)\(substring)"
var hexComponent: UInt64 = 0
Scanner(string: fullHex)
.scanHexInt64(&hexComponent)
return CGFloat(Double(hexComponent) / 255.0)
}
}
//UIColorWithHexString
static UIColor * UIColorWithHexString(NSString *hex) {
unsigned int rgb = 0;
[[NSScanner scannerWithString:
[[hex uppercaseString] stringByTrimmingCharactersInSet:
[[NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEF"] invertedSet]]]
scanHexInt:&rgb];
return [UIColor colorWithRed:((CGFloat)((rgb & 0xFF0000) >> 16)) / 255.0
green:((CGFloat)((rgb & 0xFF00) >> 8)) / 255.0
blue:((CGFloat)(rgb & 0xFF)) / 255.0
alpha:1.0];
}
使用
self.view.backgroundColor = UIColorWithHexString(@"#0F35C0");
试试这个:这段代码将从十六进制颜色字符串返回UIColor
- (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];
}
一个简明的解决方案:
// Assumes input like "#00FF00" (#RRGGBB).
+ (UIColor *)colorFromHexString:(NSString *)hexString {
unsigned rgbValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner setScanLocation:1]; // bypass '#' character
[scanner scanHexInt:&rgbValue];
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}
推荐文章
- iOS如何设置应用程序图标和启动图像
- 更改UITextField和UITextView光标/插入符颜色
- 'Project Name'是通过优化编译的——步进可能会表现得很奇怪;变量可能不可用
- 如何设置回退按钮文本在Swift
- 模拟器慢动作动画现在打开了吗?
- 如何为TableView创建NSIndexPath
- 滑动删除和“更多”按钮(就像iOS 7的邮件应用程序)
- 如何比较两个nsdate:哪个是最近的?
- 使UINavigationBar透明
- 如何改变推和弹出动画在一个基于导航的应用程序
- 删除/重置核心数据中的所有条目?
- setNeedsLayout vs. setNeedsUpdateConstraints和layoutIfNeeded vs. updateConstraintsIfNeeded
- 不区分大小写的比较
- 我怎么能得到一个uiimage的高度和宽度?
- 我如何模仿地图应用程序的底部表格?