我如何从十六进制字符串格式创建一个UIColor,如#00FF00?
当前回答
我找到了一个很好的UIColor类别,UIColor+PXExtensions。
用法:UIColor *mycolor = [UIColor pxColorWithHexValue:@"#BADA55"];
而且,为了防止链接到我的要点失败,这里是实际的实现代码:
//
// UIColor+PXExtensions.m
//
#import "UIColor+UIColor_PXExtensions.h"
@implementation UIColor (UIColor_PXExtensions)
+ (UIColor*)pxColorWithHexValue:(NSString*)hexValue
{
//Default
UIColor *defaultResult = [UIColor blackColor];
//Strip prefixed # hash
if ([hexValue hasPrefix:@"#"] && [hexValue length] > 1) {
hexValue = [hexValue substringFromIndex:1];
}
//Determine if 3 or 6 digits
NSUInteger componentLength = 0;
if ([hexValue length] == 3)
{
componentLength = 1;
}
else if ([hexValue length] == 6)
{
componentLength = 2;
}
else
{
return defaultResult;
}
BOOL isValid = YES;
CGFloat components[3];
//Seperate the R,G,B values
for (NSUInteger i = 0; i < 3; i++) {
NSString *component = [hexValue substringWithRange:NSMakeRange(componentLength * i, componentLength)];
if (componentLength == 1) {
component = [component stringByAppendingString:component];
}
NSScanner *scanner = [NSScanner scannerWithString:component];
unsigned int value;
isValid &= [scanner scanHexInt:&value];
components[i] = (CGFloat)value / 256.0f;
}
if (!isValid) {
return defaultResult;
}
return [UIColor colorWithRed:components[0]
green:components[1]
blue:components[2]
alpha:1.0];
}
@end
其他回答
上面的几个解决方案涉及到一些不必要的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
据我所知,没有从十六进制字符串到UIColor(或CGColor)的内置转换。但是,您可以很容易地为此目的编写几个函数—例如,参见iphone开发访问uicolor组件
斯威夫特的版本。作为函数或扩展使用。
Function func UIColorFromRGB(colorCode: String, alpha: Float = 1.0) -> UIColor{
var scanner = NSScanner(string:colorCode)
var color:UInt32 = 0;
scanner.scanHexInt(&color)
let mask = 0x000000FF
let r = CGFloat(Float(Int(color >> 16) & mask)/255.0)
let g = CGFloat(Float(Int(color >> 8) & mask)/255.0)
let b = CGFloat(Float(Int(color) & mask)/255.0)
return UIColor(red: r, green: g, blue: b, alpha: CGFloat(alpha))
}
Extension
extension UIColor {
convenience init(colorCode: String, alpha: Float = 1.0){
var scanner = NSScanner(string:colorCode)
var color:UInt32 = 0;
scanner.scanHexInt(&color)
let mask = 0x000000FF
let r = CGFloat(Float(Int(color >> 16) & mask)/255.0)
let g = CGFloat(Float(Int(color >> 8) & mask)/255.0)
let b = CGFloat(Float(Int(color) & mask)/255.0)
self.init(red: r, green: g, blue: b, alpha: CGFloat(alpha))
}
}
How to call
let hexColorFromFunction = UIColorFromRGB("F4C124", alpha: 1.0)
let hexColorFromExtension = UIColor(colorCode: "F4C124", alpha: 1.0)
You can also define your Hex Color
from interface builder.
试试这个:这段代码将从十六进制颜色字符串返回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];
}
这是一个接受十六进制字符串并返回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
推荐文章
- iOS如何设置应用程序图标和启动图像
- 更改UITextField和UITextView光标/插入符颜色
- 'Project Name'是通过优化编译的——步进可能会表现得很奇怪;变量可能不可用
- 如何设置回退按钮文本在Swift
- 模拟器慢动作动画现在打开了吗?
- 如何为TableView创建NSIndexPath
- 滑动删除和“更多”按钮(就像iOS 7的邮件应用程序)
- 如何比较两个nsdate:哪个是最近的?
- 使UINavigationBar透明
- 如何改变推和弹出动画在一个基于导航的应用程序
- 删除/重置核心数据中的所有条目?
- setNeedsLayout vs. setNeedsUpdateConstraints和layoutIfNeeded vs. updateConstraintsIfNeeded
- 不区分大小写的比较
- 我怎么能得到一个uiimage的高度和宽度?
- 我如何模仿地图应用程序的底部表格?