有一种简单的方法可以转换UIColor为十六进制值吗?
或者我们是否必须使用RGB组件,CGColorGetComponents然后从那里开始工作?
例如CGColorGetComponents(color.CGColor)[0] * 256?
Luc*_*nts 10
我还必须将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;
}
Run Code Online (Sandbox Code Playgroud)
欢迎所有反馈!
我会考虑使用Erica Sadun的UIColor类别.它包含许多免费功能,包括十六进制表示.它非常易于使用,只需将其添加到您正在使用它的任何类头中,或者将其添加到预编译头中以获得最大的灵活性.如果您要添加到预编译的标头,请执行类似以下操作:
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "UIColor-Expanded.h"
#endif
Run Code Online (Sandbox Code Playgroud)
然后你就可以这样使用它 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
| 归档时间: |
|
| 查看次数: |
12018 次 |
| 最近记录: |