我想从 ARGB (alpha-RGB) 值创建一个 CGColor
。有可能做到吗?怎么办?
最佳答案
如果您有要传入的值,则可以简单地执行以下操作。
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;
}
}
}
关于c# - 从 Xamarin.iOS 中的 { alpha, red, green, blue } 值创建 CGColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44385301/