關於將UIColor保存在Plist中: 我嘗試過不同的方法,但是無法做到這一點,我想保存並檢索plist文件中的顏色值。如何從Plist中加載UIColor
我無法使用nslog提取顏色的數據值並將其保存在plist中。
有沒有其他方法可以做到這一點?
我發現這個問題關於將UIColor保存在Plist中: 我嘗試過不同的方法,但是無法做到這一點,我想保存並檢索plist文件中的顏色值。如何從Plist中加載UIColor
我無法使用nslog提取顏色的數據值並將其保存在plist中。
有沒有其他方法可以做到這一點?
我發現這個問題我更喜歡用字符串來存儲顏色。那這是否顯示在下面的解析代碼(從https://github.com/xslim/TKThemeManager/blob/master/TKThemeManager.m#L162切出)
+ (UIColor *)colorFromString:(NSString *)hexString {
NSScanner *scanner = [NSScanner scannerWithString:hexString];
unsigned hex;
BOOL success = [scanner scanHexInt:&hex];
if (!success) return nil;
if ([hexString length] <= 6) {
return UIColorFromRGB(hex);
} else {
unsigned color = (hex & 0xFFFFFF00) >> 8;
CGFloat alpha = 1.0 * (hex & 0xFF)/255.0;
return UIColorFromRGBA(color, alpha);
}
}
最好的解決辦法是在以下站點:
http://arstechnica.com/apple/guides/2009/02/iphone-development-accessing-uicolor-components.ars
正從一個的UIColor字符串後,它應該是一個很容易的任務,將其保存到一個plist文件和檢索它在後面。
我做這個類別:
@implementation UIColor (EPPZRepresenter)
NSString *NSStringFromUIColor(UIColor *color)
{
const CGFloat *components = CGColorGetComponents(color.CGColor);
return [NSString stringWithFormat:@"[%f, %f, %f, %f]",
components[0],
components[1],
components[2],
components[3]];
}
UIColor *UIColorFromNSString(NSString *string)
{
NSString *componentsString = [[string stringByReplacingOccurrencesOfString:@"[" withString:@""] stringByReplacingOccurrencesOfString:@"]" withString:@""];
NSArray *components = [componentsString componentsSeparatedByString:@", "];
return [UIColor colorWithRed:[(NSString*)components[0] floatValue]
green:[(NSString*)components[1] floatValue]
blue:[(NSString*)components[2] floatValue]
alpha:[(NSString*)components[3] floatValue]];
}
@end
所使用的NSStringFromCGAffineTransform相同的格式。這實際上是在[GitHub]的[eppz!kit] [1]中更大規模的plist對象代表的一部分。
對於一個快速的解決方案(但也許不是最漂亮的一個):
0xff00e3
下面是一個代碼示例的宏處理它:
// Add this code to some include, for reuse
#define UIColorFromRGBA(rgbValue, alphaValue) ([UIColor colorWithRed:((CGFloat)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((CGFloat)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((CGFloat)(rgbValue & 0xFF))/255.0 \
alpha:alphaValue])
// This goes into your controller/view
NSDictionary *myPropertiesDict = [NSDictionary dictionaryWithContentsOfFile:...];
UIColor *titleColor = UIColorFromRGBA([myPropertiesDict[@"titleColor"] integerValue], 1.0);
進入顏色hexdecimal後,編輯的plist將展示它作爲一個十進制數。不太好。作爲開發人員,您通常會複製粘貼來自設計文檔的顏色,因此讀取顏色值的需求並不那麼大。
只是要注意的是,紅色,綠色,藍色值是0.0-1.0不0-255因此通過255除以他們得到正確的值 - 這讓我出去了一會兒。 – amergin 2014-02-07 13:50:21
這是爲了存儲在'plist'中,你可能想要「設計」'plist'中的顏色。對於RGB轉換助手,請參閱http://stackoverflow.com/questions/13224206/how-do-i-create-an-rgb-color-with-uicolor/21297254#21297254和http://stackoverflow.com/questions/ 437113 /如何對獲得-RGB值從 - 的UIColor/21296829#21296829。 – Geri 2014-02-07 15:42:30