动态加载字体并使用

看到这个手写模拟器想到的动态加载字体。

 

界面:

源码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace HandwritingSimulator
{
    public partial class Form1 : Form
    {
        Dictionary<string, Font> keyFonts = new Dictionary<string, Font>();
        Graphics g;
        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
            g = panel1.CreateGraphics();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (Directory.Exists("fonts"))
            {
                var fonts = Directory.GetFiles("fonts");
                // 打开字体文件 
                PrivateFontCollection privateFonts = new PrivateFontCollection();
                foreach (var item in fonts)
                { 
                    // 加载字体
                    privateFonts.AddFontFile(item);  
                }
                for (int i = 0; i < privateFonts.Families.Length; i++)
                {
                    Font font = new Font(privateFonts.Families[i], 36);
                    keyFonts[font.Name] = font;
                    comboBox1.Items.Add(font.Name);
                } 
            }
            comboBox1.SelectedIndex = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            g.Clear(Color.White);
            var font =new Font( keyFonts[comboBox1.Text].FontFamily,(float)numericUpDown1.Value); 
            g.DrawString(richTextBox1.Text, font, new SolidBrush(button2.BackColor),new Point(0,0));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ColorDialog dialog = new ColorDialog(); 
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                // 获取选择的颜色
                button2.BackColor = dialog.Color;
            }
        }
    }
}

 

Source: https://files.cnblogs.com/files/Zingu/HandwritingSimulator.rar?t=1692685211&download=true

 

posted @ 2023-08-22 14:21  后跳  阅读(104)  评论(0编辑  收藏  举报