【C#】将IconFont的字体图标库转为图片

字体库的图标是从https://www.iconfont.cn/下载来的。使用的是扩展名为TTF的字体库文件。把TTF文件导入到项目资源中。

Graphics这个类有个方法DrawString,可以把文字直接画出来。但是效果不是很好,需要对最后画出来的图片做处理。最直观的影响最终效果的是:图片带着空白部分。

字体图标库处理:

1.定义枚举类:

    /// <summary>
    /// 图标枚举
    /// </summary>
    public enum IconFontChars
    {
        _None = 32,
        /// <summary>
        /// AI
        /// </summary>
        AI = 0xec66,
        /// <summary>
        /// api接口
        /// </summary>
        apiJK_api接口 = 0xe697,
        /// <summary>
        /// API接入
        /// </summary>
        APIJR_API接入 = 0xec19,
        /// <summary>
        /// 方块+(原名称)
        /// </summary>
        FK_方块 = 0xec06,
        /// <summary>
        /// 方块-
        /// </summary>
        FK_方块1 = 0xec07
     }

上面这个枚举是写了一个工具,把下图的UniCode部分提取出来

工具下载

2.定义图标类:

public class IconFont
    {
        /// <summary>
        /// 默认字体图标
        /// </summary>
        private IconFontChars _Icon = IconFontChars._None;
        /// <summary>
        /// 默认字体图标尺寸
        /// </summary>
        private Size _IconSize = new Size(24, 24);
        /// <summary>
        /// 默认字体图标前颜色
        /// </summary>
        private Color _ForeColor = Color.FromArgb(51, 51, 51);//#333333
        /// <summary>
        /// 默认字体图标背景色
        /// </summary>
        private Color _BackColor = Color.Transparent;
        /// <summary>
        /// 默认 图标到边缘的距离
        /// </summary>
        private Padding _Padding = new Padding(0);

        public IconFontChars Icon { get { return _Icon; } set { _Icon = value; } }
        public Size IconSize { get { return _IconSize; } set { _IconSize = value; } }
        public Color ForeColor { get { return _ForeColor; } set { _ForeColor = value; } }
        public Color BackColor { get { return _BackColor; } set { _BackColor = value; } }
        public Padding Padding { get { return _Padding; }set { _Padding = value; } }

        /// <summary>
        /// 用于表格中的状态 YES
        /// </summary>
        public static Bitmap StatusYes
        {
            get
            {
                return IconFontAwesome.ToImage(new IconFont
                {
                    Icon = IconFontChars.DG_对勾1,
                    Padding = new Padding(6),
                    ForeColor = Color.Green
                });
            }
        }

        /// <summary>
        /// 用于表格中的状态 NO
        /// </summary>
        public static Bitmap StatusNo
        {
            get
            {
                return IconFontAwesome.ToImage(new IconFont
                { Icon = IconFontChars.GB_关闭1,
                    Padding = new Padding(6)
                });
            }
        }

        /// <summary>
        /// 默认图标
        /// </summary>
        /// <param name="iconFontChars"></param>
        /// <returns></returns>
        public static Bitmap Default(IconFontChars iconFontChars)
        {
            return Default(iconFontChars, new Padding(0), BaseStyle.ToolBarIconColor);
        }

        /// <summary>
        /// 默认图标
        /// </summary>
        /// <param name="iconFontChars"></param>
        /// <param name="padding"></param>
        /// <returns></returns>
        public static Bitmap Default(IconFontChars iconFontChars,Padding padding)
        {
            return Default(iconFontChars, padding, BaseStyle.ToolBarIconColor);
        }

        /// <summary>
        /// 默认图标
        /// </summary>
        /// <param name="iconFontChars"></param>
        /// <param name="padding"></param>
        /// <param name="foreColor"></param>
        /// <returns></returns>
        public static Bitmap Default(IconFontChars iconFontChars, Padding padding,Color foreColor)
        {
            return IconFontAwesome.ToImage(new IconFont
            {
                ForeColor = foreColor,
                Icon = iconFontChars,
                Padding = padding
            });
        }
    }

 3.将字体库图标转成Bitmap

public static class IconFontAwesome
    {
        static PrivateFontCollection privateFonts = new PrivateFontCollection();
        static FontFamily fontAwesome;

        /// <summary>
        /// 获取IconFontAwesome字体样式
        /// </summary>
        public static FontFamily FontAwesome
        {
            get
            {
                if (fontAwesome == null)
                {
                    byte[] f = Properties.Resources.iconfont;
                    unsafe
                    {
                        fixed (byte* pFontData = f)
                        {
                            privateFonts.AddMemoryFont((IntPtr)pFontData, f.Length);
                        }
                    }
                    fontAwesome = privateFonts.Families[0];
                }
                return fontAwesome;
            }
        }

        /// <summary>
        /// 将IconFont转图片
        /// </summary>
        /// <param name="iconFont"></param>
        /// <returns></returns>
        public static Bitmap ToImage(IconFont iconFont)
        {
            if (iconFont == null || iconFont.Icon == IconFontChars._None)
            {
                return null;
            }

            Graphics g;
            Bitmap srcBitmap = new Bitmap(1, 1);
            StringFormat format = new StringFormat(StringFormatFlags.NoWrap);
            format.LineAlignment = StringAlignment.Center;
            format.Alignment = StringAlignment.Center;

            Rectangle rect = Rectangle.Empty;

            //字号五倍放大
            int fontSize = iconFont.IconSize.Width * 5;
            if (iconFont.IconSize.Width < iconFont.IconSize.Height)
            {
                fontSize = iconFont.IconSize.Height * 5;
            }

            string text = ((char)iconFont.Icon).ToString();
            Font font = new System.Drawing.Font(FontAwesome, fontSize, System
                .Drawing.FontStyle.Regular, GraphicsUnit.Point);

            //计算原始图标
            if (rect == Rectangle.Empty)
            {
                g = Graphics.FromImage(srcBitmap);
                //计算绘制文字所需的区域大小(根据宽度计算长度),重新创建矩形区域绘图
                SizeF sizef = g.MeasureString(text, font, PointF.Empty, format);

                int width = (int)(sizef.Width + 1);
                int height = (int)(sizef.Height + 1);
                rect = new Rectangle(0, 0, width, height);
                srcBitmap.Dispose();
                g.Dispose();

                srcBitmap = new Bitmap(width, height);
            }
            g = Graphics.FromImage(srcBitmap);
            SetGraphics(g);
            //绘制原始图标(不用solidbrush)
            LinearGradientBrush iconBrush = new LinearGradientBrush(
                rect, iconFont.ForeColor, iconFont.ForeColor, 0f, true);
            //直接画出来的字符,会带空白部分,所以要把空白裁剪掉
            g.DrawString(text, font, iconBrush, rect, format);
            //重新计算位图尺寸和裁剪坐标
            FixBitmapArgs args = GetBitmapSizeP(srcBitmap,iconFont.ForeColor);
            //不带空白部分的位图,为原始输出位图
            Bitmap bmpOut1 = new Bitmap(args.Size.Width, args.Size.Height);
            Graphics g4 = Graphics.FromImage(bmpOut1);
            SetGraphics(g4);
            //裁剪有效图标区域,去掉空白部分
            g4.DrawImage(srcBitmap, new Rectangle(0, 0, args.Size.Width, args.Size.Height),
                new Rectangle(args.MinPoint.X, args.MinPoint.Y, args.Size.Width, args.Size.Height), GraphicsUnit.Pixel);
            //图标的尺寸
            Size imgSize = new Size();
            int w = iconFont.IconSize.Width - (iconFont.Padding.Left + iconFont.Padding.Right);
            if (w < 0)
            {
                w = 1;
            }
            int h = iconFont.IconSize.Height - (iconFont.Padding.Top + iconFont.Padding.Bottom);
            if (h < 0)
            {
                h = 1;
            }
            imgSize.Width = w;
            imgSize.Height = h;
            //压缩图标到指定尺寸
            Bitmap resultBitmap1 = ImageConverter.ResizeImage(bmpOut1,imgSize);

            //输出
            Bitmap outputImg = new Bitmap(iconFont.IconSize.Width, iconFont.IconSize.Height);
            Graphics g5 = Graphics.FromImage(outputImg);
            SetGraphics(g5);
            //画图标背景
            g5.FillRectangle(new SolidBrush(iconFont.BackColor), new RectangleF(0, 0, iconFont.IconSize.Width, iconFont.IconSize.Height));
            //图标
            g5.DrawImage(resultBitmap1, new PointF(iconFont.Padding.Left, iconFont.Padding.Top));
            //释放资源
            format.Dispose();
            iconBrush.Dispose();
            srcBitmap.Dispose();
            bmpOut1.Dispose();
            resultBitmap1.Dispose();
            g.Dispose();
            g4.Dispose();
            return outputImg;
        }

        /// <summary>
        /// 从原始图标Bitmap中提取有效图标的尺寸和最小最大坐标
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="selectorColor"></param>
        /// <returns></returns>
        private static FixBitmapArgs GetBitmapSizeP(Bitmap bitmap,Color selectorColor)
        {
            Size size = Size.Empty;
            Point minPoint = Point.Empty;
            Point maxPoint = Point.Empty;
            int minPointX = 100000000;
            int maxPointX = 0;
            int minPointY = 100000000;
            int maxPointY = 0;

            for (int x = 0; x < bitmap.Width; x++)
            {
                for (int y = 0; y < bitmap.Height; y++)
                {
                    Color color = bitmap.GetPixel(x, y);
                    if (color.R == selectorColor.R&&color.G==selectorColor.G&&color.B==selectorColor.B)
                    {
                        if (x < minPointX)
                        {
                            minPointX = x;
                        }
                        if (x > maxPointX)
                        {
                            maxPointX = x;
                        }
                        if (y < minPointY)
                        {
                            minPointY = y;
                        }
                        if (y > maxPointY)
                        {
                            maxPointY = y;
                        }
                    }
                }
            }
            size = new Size(maxPointX - minPointX, maxPointY - minPointY);
            minPoint = new Point(minPointX, minPointY);
            maxPoint = new Point(maxPointX, maxPointY);
            return new FixBitmapArgs { Size=size,MinPoint=minPoint,MaxPoint=maxPoint};
        }

        /// <summary>
        /// 设置Graphics属性
        /// </summary>
        /// <param name="g"></param>
        private static void SetGraphics(Graphics g)
        {
            g.SmoothingMode = SmoothingMode.AntiAlias;  //使绘图质量最高,即消除锯齿
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        }
    }

    internal class FixBitmapArgs
    {
        public Size Size { get; set; }
        public Point MinPoint { get; set; }
        public Point MaxPoint { get; set; }
    }

ImageConverter类:

    /// <summary>
    /// 图片转换工具
    /// </summary>
    public class ImageConverter
    {
        /// <summary>
        /// 重置图片尺寸,该方法会释放来源文件
        /// </summary>
        /// <param name="mg"></param>
        /// <param name="newSize"></param>
        /// <returns></returns>
        public static Bitmap ResizeImage(Bitmap mg, Size newSize)
        {
            double ratio = 0d;
            double myThumbWidth = 0d;
            double myThumbHeight = 0d;
            int x = 0;
            int y = 0;
            Bitmap bp;

            if ((mg.Width / Convert.ToDouble(newSize.Width)) > (mg.Height /
            Convert.ToDouble(newSize.Height)))
                ratio = Convert.ToDouble(mg.Width) / Convert.ToDouble(newSize.Width);
            else
                ratio = Convert.ToDouble(mg.Height) / Convert.ToDouble(newSize.Height);
            myThumbHeight = Math.Ceiling(mg.Height / ratio);
            myThumbWidth = Math.Ceiling(mg.Width / ratio);

            Size thumbSize = new Size((int)newSize.Width, (int)newSize.Height);
            bp = new Bitmap(newSize.Width, newSize.Height);
            x = (newSize.Width - thumbSize.Width) / 2;
            y = (newSize.Height - thumbSize.Height);
            System.Drawing.Graphics g = Graphics.FromImage(bp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            Rectangle rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
            g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);

            mg.Dispose(); //释放被占用的文件
            return bp;
        }
    }

 

 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值