我如何从十六进制字符串格式创建一个UIColor,如#00FF00?
当前回答
大多数发布的解决方案使用了Scanner,但至少在现代Swift中你并不真正需要它。相反,你可以简单地使用UInt init和基数16,然后使用基本的二进制操作来获得UIColor组件:
func stringToColor(color: String) -> UIColor {
guard let i = UInt(color, radix: 16) else {
return UIColor.white
}
return UIColor(
red: CGFloat((i & 0xFF0000) >> 16) / 255.0,
green: CGFloat((i & 0xFF00) >> 8) / 255.0,
blue: CGFloat(i & 0xFF) / 255.0,
alpha: 1.0
)
}
这个解决方案期望输入像“FF00FF”,你可能需要删除前面的哈希符号(#),如果你的字符串中有一个。
其他回答
您可以使用各种在线工具将HEX字符串转换为实际的UIColor。查看uicolor.org或UI颜色选择器。输出将被转换为Objective-C代码,如下所示:
[UIColor colorWithRed:0.93 green:0.80 blue:0.80 alpha:1.0];
可以嵌入到应用程序中。希望这能有所帮助!
Xamarin的。iOS你可以使用下面的宏来代替宏:
public UIColor UIColorFromHexValue(int value, float alpha = 1f) =>
UIColor.FromRGBA(
((value & 0xFF0000) >> 16) / 255.0f,
((value & 0x00FF00) >> 16) / 255.0f,
((value & 0x0000FF) >> 16) / 255.0f,
alpha);
用法类似:
label.TextColor = UIColorFromHexValue(0xBC1128);
有一个很好的帖子是关于如何解决OP的问题,从十六进制字符串中提取UIColor。下面给出的解决方案与其他解决方案不同,因为它支持字符串值,可能包括'0x'或'#'前缀的十六进制字符串表示…(请参阅使用)
这是主要的部分…
- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
// Convert hex string to an integer
unsigned int hexint = [self intFromHexString:hexStr];
// Create a color object, specifying alpha as well
UIColor *color =
[UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255
green:((CGFloat) ((hexint & 0xFF00) >> 8))/255
blue:((CGFloat) (hexint & 0xFF))/255
alpha:alpha];
return color;
}
助手方法……
- (unsigned int)intFromHexString:(NSString *)hexStr
{
unsigned int hexInt = 0;
// Create scanner
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
// Tell scanner to skip the # character
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];
// Scan hex value
[scanner scanHexInt:&hexInt];
return hexInt;
}
用法:
NSString *hexStr1 = @"123ABC";
NSString *hexStr2 = @"#123ABC";
NSString *hexStr3 = @"0x123ABC";
UIColor *color1 = [self getUIColorObjectFromHexString:hexStr1 alpha:.9];
NSLog(@"UIColor: %@", color1);
UIColor *color2 = [self getUIColorObjectFromHexString:hexStr2 alpha:.9];
NSLog(@"UIColor: %@", color2);
UIColor *color3 = [self getUIColorObjectFromHexString:hexStr3 alpha:.9];
NSLog(@"UIColor: %@", color3);
完整的参考文章
Swift 2 +
我已经将这个解决方案移植到Swift 2.2。注意,我已经将alpha参数更改为使用默认设置为1.0。我还根据Swift 2.2中的NSScanner类的要求将int类型更新为UInt32。
func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {
// Convert hex string to an integer
let hexint = Int(self.intFromHexString(hexString))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
// Create color object, specifying alpha as well
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
func intFromHexString(hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
// Create scanner
let scanner: NSScanner = NSScanner(string: hexStr)
// Tell scanner to skip the # character
scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#")
// Scan hex value
scanner.scanHexInt(&hexInt)
return hexInt
}
斯威夫特 4+
采用与swift 4相同的变化逻辑,
func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {
// Convert hex string to an integer
let hexint = Int(self.intFromHexString(hexStr: hexString))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
// Create color object, specifying alpha as well
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
func intFromHexString(hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
// Create scanner
let scanner: Scanner = Scanner(string: hexStr)
// Tell scanner to skip the # character
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
// Scan hex value
scanner.scanHexInt32(&hexInt)
return hexInt
}
Swift 5 (iOS 13)+
下面显示了在SDK弃用scanHexInt32的情况下工作的更新。我将代码封装到Swift playground文件中。
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = colorWithHexString(hexString: "22F728")
view.addSubview(label)
self.view = view
}
func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {
// Convert hex string to an integer
let hexint = Int(self.intFromHexString(hexStr: hexString))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
// Create color object, specifying alpha as well
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
func intFromHexString(hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
// Create scanner
let scanner: Scanner = Scanner(string: hexStr)
// Tell scanner to skip the # character
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
// Scan hex value
hexInt = UInt32(bitPattern: scanner.scanInt32(representation: .hexadecimal) ?? 0)
return hexInt
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
彩色十六进制参考 HTML颜色名称和代码 十六进制颜色编码
使用任何转换器网站将十六进制颜色转换为RGB值(如果你谷歌“十六进制到RGB”,你会看到一吨)。例如,这个:http://www.rgbtohex.net/hextorgb/
然后将颜色属性更改为UIColor。例子:
self.profilePicture.layer.borderColor = [UIColor colorWithRed:0 green:167 blue:142 alpha:1.0].CGColor;
十六进制颜色值是:00a78e转换为RGB: R: 0 G: 167 B: 142
如果你给出的RGB值不在0到1.0之间,你必须将它们除以255。例子:
self.profilePicture.layer.borderColor = [UIColor colorWithRed:83.00/255.0 green:123.00/255.0 blue:53.00/255.0 alpha:1.0].CGColor;
我最终为UIColor创建了一个类别,我可以在我的其他项目中重用,并添加了这个函数:
+ (UIColor *)colorFromHex:(unsigned long)hex
{
return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0
green:((float)((hex & 0xFF00) >> 8))/255.0
blue:((float)(hex & 0xFF))/255.0
alpha:1.0];
}
用法是这样的:
UIColor *customRedColor = [UIColor colorFromHex:0x990000];
这比传递字符串并将其转换为数字然后移位位要快得多。
你也可以从你的.pch文件中导入类别,这样你就可以很容易地在你的应用程序中到处使用colorFromHex,就像它内置到UIColor中一样:
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
// Your other stuff here...
#import "UIColor+HexColor.h"
#endif
推荐文章
- 我如何在我的iOS应用程序中每n分钟得到一个后台位置更新?
- 如何使用iOS创建GUID/UUID
- 禁用所呈现视图控制器的交互式撤销
- 点击按钮时如何打开手机设置?
- 如何使用UIVisualEffectView来模糊图像?
- 如何修复UITableView分隔符在iOS 7?
- 故事板中的自定义单元格行高设置没有响应
- 在Swift中使用自定义消息抛出错误/异常的最简单方法?
- 如何在Swift中获得唯一的设备ID ?
- 复制文本到剪贴板与iOS
- 在Swift中根据字符串计算UILabel的大小
- 如何调用手势点击在UIView编程在迅速
- 我如何隐藏在一个Swift iOS应用程序的状态栏?
- 在iPad上使用iOS 8正确呈现UIAlertController
- 尝试将一个非属性列表对象设置为NSUserDefaults