WPF string转color ,brush

SubjectBorderTiele.BorderBrush = new 
SolidColorBrush((Color)ColorConverter.ConvertFromString("#2DE9B1"));
using MediaBrushes = System.Windows.Media.Brushes;

ColorConverter

    public class ColorHelper
    {
        /// <summary>
        /// 色码转色刷
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static SolidColorBrush StringToBrush(string value)
        {
            // 因为色刷支持空值,所以输入为空时返回null
            if (string.IsNullOrEmpty(value)) return MediaBrushes.Transparent;
            try
            {
                // 格式验证
                var res = ColorStringFormatVerify(value);
                // 判断透明色
                if (IsTransparent(res) || string.IsNullOrEmpty(res))
                {
                    return MediaBrushes.Transparent;
                }
                // 转换色码
                var obj = new BrushConverter().ConvertFromString(res);
                if (obj == null) throw new Exception("转换失败");
                return (SolidColorBrush)obj;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 判断是否为透明色码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsTransparent(string value)
        {
            var res = value.Trim(' ', '#');
            return string.Equals(res.ToUpper(), "00FFFFFF", StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 色码格式化验证
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ColorStringFormatVerify(string value)
        {
            var res = value.Trim(' ', '#');
            // 判断空值
            if (string.IsNullOrEmpty(res))
            {
                throw new Exception("输入色码为空");
            }
            // 判断色码十六进制格式
            if (!Regex.IsMatch(res, @"[A-Fa-f0-9]+$"))
            {
                throw new Exception("输入色码格式错误");
            }
            // 判断色码长度
            if (res.Length != 6 && res.Length != 8)
            {
                throw new Exception("输入色码长度错误");
            }
            var length = res.Length == 6 ? 6 : 8;
            // 补齐位数
            res = res.PadRight(length, '0');
            res = res.Substring(0, length);
            res = "#" + res;
            return res;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值