用BitArray类提取汉字的字模

位数组类BitArray在using System.Collections命名空间。这里我用这个类来提取汉字的字模。
 
首先将一个汉字用DrawString方法画出:
Bitmap bm = new Bitmap(16, 16);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
Graphics g = Graphics.FromImage(bm);
g.DrawString(str, new Font("宋体", 12), Brushes.Black, new Rectangle(0, 0, 16, 16), sf);
 
然后就可以用BitArray类提取字模:
            BitArray ba = new BitArray(256);
            for (int i=0; i < bm.Height; i++)
            {
                for (int j=0; j < bm.Width; j++)
                {
                    if (bm.GetPixel(j,i ) == Color.FromArgb(0, 0, 0))
                        ba.Set(i*16+j,false);
                    else
                        ba.Set(i*16+j,true);
                }
            }
 
把提取的字模显示出来的函数:
        private void showChar(BitArray bar)
        {
            for (int i = 0; i < bar.Length; i++)
            {
                if (i % 16 == 0)
                    textBox2.Text += "\r\n";
                if(bar.Get(i)==true)
                    textBox2.Text += "■";
                else
                    textBox2.Text += "□";
            }
        }
 
把提取的字模转换成16进制表示的函数:
       private void changeChar(BitArray bar)
        {
            int temp = 0;
            int i=0;
            int j = 0;
            foreach (bool b in bar)
            {
                i++;
                j++;
                if (i == 8) { i = 0; label2.Text += temp.ToString("X2") + " "; temp = 0; }
                if (j == 64) { j = 0; label2.Text += "\r\n"; }
                if(b==true)
                temp |=(1<<i);
            }
        }
 
附件是源代码:

本文出自 “锦州数据恢复-硬盘之家” 博客,谢绝转载!

你可能感兴趣的:(职场,休闲,字模)