WPF控件帮助类,实现字体自适应,图片上传解码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Controls.Helper
{
    public class ControlHelper
    {
        /// <summary>
        /// 获得指定元素的父元素
        /// </summary>
        /// <typeparam name="T">指定页面元素</typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T GetParentObject<T>(DependencyObject obj) where T : FrameworkElement
        {
            DependencyObject parent = VisualTreeHelper.GetParent(obj);

            while (parent != null)
            {
                if (parent is T)
                {
                    return (T)parent;
                }

                parent = VisualTreeHelper.GetParent(parent);
            }

            return null;
        }

        /// <summary>
        /// 根据宽度自适应字体大小
        /// </summary>
        /// <returns></returns>
        public static double AdjustFontSize(double srcSize, double minSize)
        {
               double srcScale = 1920f / 1080f;
            double curScale = SystemParameters.PrimaryScreenWidth / SystemParameters.PrimaryScreenHeight;
            double scale = curScale / srcScale;
            double fontSize = srcSize * scale;

            if (fontSize > srcSize)
                fontSize = srcSize;

            if (fontSize < minSize)
                fontSize = minSize;

            return fontSize;
        }

        /// <summary>
        /// 图片上传 Base64解码
        /// </summary>
        /// <param name="dataURL">Base64数据</param>
        /// <returns>返回一个相对路径</returns>
        public static BitmapImage decodeBase64ToImage(string dataURL)
        {
            string base64 = dataURL.Substring(dataURL.IndexOf(",") + 1);      //将‘,’以前的多余字符串删除
            BitmapImage bi = new BitmapImage();
            try
            {
                byte[] arr = Convert.FromBase64String(base64);//将纯净资源Base64转换成等效的8位无符号整形数组
                bi.BeginInit();
                bi.StreamSource = new System.IO.MemoryStream(arr);
                bi.EndInit();
                //ms.Close();//关闭当前流,并释放所有与之关联的资源
            }
            catch (Exception)
            {
            }
            return bi;
         }
    }
}
                        

  

posted on 2023-09-11 09:18  潇潇烟雨  阅读(266)  评论(0编辑  收藏  举报