我想从ARGB(alpha-RGB)值创建CGColor
。有可能吗?怎么样?
答案 0 :(得分:2)
如果您要传入值,则可以执行以下操作。
UIColor.FromRGBA(red, green, blue, alpha).CGColor;
我们使用一个小助手类来将哈希值转换为UIColors,只需要它就可以了。只需传入哈希值(" #ffffff")。然后在它返回的UIColor上调用.CGColor,或者相应地调整类。
class Colors
{
public static UIColor FromHexString(string hexValue, float alpha = 1.0f)
{
try
{
string colorString = hexValue.Replace("#", "");
float red, green, blue;
switch (colorString.Length)
{
case 3: // #RGB
{
red = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(0, 1)), 16) / 255f;
green = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(1, 1)), 16) / 255f;
blue = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(2, 1)), 16) / 255f;
return UIColor.FromRGBA(red, green, blue, alpha);
}
case 6: // #RRGGBB
{
red = Convert.ToInt32(colorString.Substring(0, 2), 16) / 255f;
green = Convert.ToInt32(colorString.Substring(2, 2), 16) / 255f;
blue = Convert.ToInt32(colorString.Substring(4, 2), 16) / 255f;
return UIColor.FromRGBA(red, green, blue, alpha);
}
case 8: // #RRGGBBAA
{
red = Convert.ToInt32(colorString.Substring(0, 2), 16) / 255f;
green = Convert.ToInt32(colorString.Substring(2, 2), 16) / 255f;
blue = Convert.ToInt32(colorString.Substring(4, 2), 16) / 255f;
alpha = Convert.ToInt32(colorString.Substring(6, 2), 16) / 255f;
return UIColor.FromRGBA(red, green, blue, alpha);
}
default:
throw new ArgumentOutOfRangeException(string.Format("Invalid color value {0} is invalid. It should be a hex value of the form #RBG, #RRGGBB", hexValue));
}
}
catch (Exception genEx)
{
return null;
}
}
}