在此代码着色返回值= 0X90EE90
coloring=[colorall objectForKey:globallinecolor];
shapeLayer.strokeColor = UIColorFromRGB(coloring).CGColor;
但是这段代码给了我错误,任何人都可以帮助我如何通过UIColorFromRGB传递值。
您正在检索NSString对象(着色),但宏需要一个整数。
要从十六进制字符串中获取整数,可以使用NSScanner类。
沿着:
unsigned int hexValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:coloring];
[scanner setScanLocation:0]; // depends on your exact string format you may have to use location 1
[scanner scanHexInt:&hexValue];
shapeLayer.strokeColor = UIColorFromRGB(hexValue).CGColor;
创建方法宏,如:
#define UIColorFromRGB(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]
并用作:
self.backgroundColor = UIColorFromRGB(0X90EE90);
虽然OP在ObjC
问道,但有人可能会来这里寻找Swift
:
func UIColorFromHex(rgbValue: UInt) -> UIColor {
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)
)
}
并用作:
let someColor = UIColorFromHex(0x27a9e0)
我有类似的问题,我在网上找到了这个解决方案(现在找不到),这个解决方案接近别人放在这里但可能有所帮助。
试试这个,
coloring=[colorall objectForKey:globallinecolor];
shapeLayer.strokeColor = UIColorFromRGB(colourFromHexString:coloring).CGColor;
然后
-(UIColor *)colourFromHexString:(NSString *)hexString
{
unsigned rgbValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner setScanLocation:2]; // bypass '#' character
[scanner scanHexInt:&rgbValue];
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}
或者您可以将十六进制值保存为整数,如下所示:
[defaults setInteger:0x640800 forKey:@"in"];
然后做这样的事情:
defaults = [NSUserDefaults standardUserDefaults];
long rgbCode = [defaults integerForKey:packageName];
_languageButton.backgroundColor = UIColorFromRGB(rgbCode);