有没有简单的方法将UIColor
转换为十六进制值?
或者我们必须得到与CGColorGetComponents
的RGB组件,然后从那里解决它?UIColor到十六进制(网络色)
例如CGColorGetComponents(color.CGColor)[0] * 256
?
有没有简单的方法将UIColor
转换为十六进制值?
或者我们必须得到与CGColorGetComponents
的RGB组件,然后从那里解决它?UIColor到十六进制(网络色)
例如CGColorGetComponents(color.CGColor)[0] * 256
?
我会考虑使用Erica Sadun的UIColor类别。它包含许多免费的功能,包括十六进制表示。使用起来非常简单,只需将其添加到您使用的任何类头中,或者将其添加到预编译头以获得最大的灵活性。 如果您要添加到预编译的头,这样做类似这样的事情:
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "UIColor-Expanded.h"
#endif
那么你可以使用它像这样NSLog(@"%@", [myColor hexStringFromColor]);
GitHub的链接的UIColor类别:https://github.com/erica/uicolor-utilities
ArsTechnica有关它的文章:http://arstechnica.com/apple/guides/2009/02/iphone-development-accessing-uicolor-components.ars
据我所知,没有任何内置解决方案。
但请注意,您应该乘以255
而不是256
。
获取十六进制表示法是一件容易的事情,所以您不会有很多麻烦来手动构建字符串。
NSLog(@"%X%X%X", redInteger, greenInteger, blueInteger);
我也必须将UIColor转换为它的十六进制组件。
正如lewiguez已经指出的那样,在github有一个很好的类别,可以完成所有这些工作。
但是因为我想了解它是如何完成的,我对RGB颜色做了自己的简单实现。
+ (NSString*)colorToWeb:(UIColor*)color
{
NSString *webColor = nil;
// This method only works for RGB colors
if (color &&
CGColorGetNumberOfComponents(color.CGColor) == 4)
{
// Get the red, green and blue components
const CGFloat *components = CGColorGetComponents(color.CGColor);
// These components range from 0.0 till 1.0 and need to be converted to 0 till 255
CGFloat red, green, blue;
red = roundf(components[0] * 255.0);
green = roundf(components[1] * 255.0);
blue = roundf(components[2] * 255.0);
// Convert with %02x (use 02 to always get two chars)
webColor = [[NSString alloc]initWithFormat:@"%02x%02x%02x", (int)red, (int)green, (int)blue];
}
return webColor;
}
欢迎任何反馈!
这种方法完美的工作,谢谢! – BFeher 2014-09-02 05:16:03
除了广泛使用的基于字符串的解决方案之外,这里是基于十六进制(整数)的解决方案。用法:
UIColor* color = lf_rgb(0x120aef);
log(@"color %.6x", color.hex_rgb);
然后你会得到“颜色120aef”。我会在https://github.com/superarts/LCategory这些代码,也可以复制,粘贴到自己的代码库也:
#define lf_rgb(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
@interface UIColor (lc_rgb)
- (NSInteger)hex_rgb;
@end
@implementation UIColor (lc_rgb)
- (NSInteger)hex_rgb
{
CGFloat r, g, b, a;
BOOL result = [self getRed:&r green:&g blue:&b alpha:&a];
// log(@"rgba: %f, %f, %f, %f", r * 255, g * 255, b * 255, a * 255);
if ((result == NO) || (a != 1.0f))
return -1;
return
(NSInteger)(r * 255) * 256 * 256 +
(NSInteger)(g * 255) * 256 +
(NSInteger)(b * 255) * 1;
}
@end
这是我做的如何与斯威夫特3做的:
extension UIColor {
var hex:String{
get{
var red:CGFloat = 0
var blue:CGFloat = 0
var green:CGFloat = 0
var alpha:CGFloat = 0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
let rgb:Int = (Int)(red*255)<<16 | (Int)(green*255)<<8 | (Int)(blue*255)<<0
return String.localizedStringWithFormat("#%06x", rgb)
}
}
}
或者你可以使其成为一种方法。我只是喜欢color.hex
外观与color.hex()
。
伟大的图书馆。感谢这一点。 – fes 2011-12-31 18:38:33
没问题。希望可以帮助你! – lewiguez 2011-12-31 19:48:43