代码改变世界

c# 文字组合文字

2012-08-13 16:13  Sun.M  阅读(808)  评论(0编辑  收藏  举报

这个标题很不好起,什么叫文字组合文字?通过下图就明白了:

image

可以看到,这个M是由很多“*”组成,这就是文字组合文字。

其实思路很简单,就是通过将需要产生的组合文字,先绘制到一个Bitmap中,然后通过判断Bitmap像素来组合我们需要的文字。请看以下很简略的代码:

  private Bitmap ConvertCharToBitmap(char c) {
            Bitmap result = new Bitmap(40, 40);
            Graphics g = Graphics.FromImage(result);
            g.Clear(Color.White);

            Font drawFont = new Font("Courier New", 40, GraphicsUnit.Pixel);
            g.DrawString(c.ToString(), drawFont, new SolidBrush(Color.Black), new PointF(0, 0));

            return result;
        }

        private string ConvertBitmapToStrings(Bitmap bmp) {
            string result = "";
            for (int h = 0; h < bmp.Height; h++) {
                for (int w = 0; w < bmp.Width; w++) {
                    if (bmp.GetPixel(w, h).R < 250) { //表示文字区域
                        result += "*";
                    } else {  //表示空白
                        result += " ";
                    }
                }
                result += Environment.NewLine;
            }
            return result;
        }

 

一共两个方法,一个是将字符转换成图片,另一个再将图片转换成字符串,调用如下:

 private void btnBuild_Click(object sender, EventArgs e) {
            if (string.IsNullOrEmpty(txtAWord.Text)) {
                MessageBox.Show("请输入一个字符!", "错误提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtAWord.Focus();
                return;
            }

            txtOutput.Text = ConvertBitmapToStrings(ConvertCharToBitmap(txtAWord.Text[0]));
        }

蛮好玩的,大家可以将它扩展和增强一下,比如任何图片组合成文字(主要根据灰度),比如不只是一个字符,而是字符串(这个比上个要简单很多)。