Skip to main content
 首页 » 编程设计

c#之从 Xamarin.iOS 中的 { alpha, red, green, blue } 值创建 CGColor

2024年02月27日71davidwang456

我想从 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; 
            } 
        } 
    }