c# 文字组合文字
2012-08-13 16:13 Sun.M 阅读(832) 评论(0) 收藏 举报这个标题很不好起,什么叫文字组合文字?通过下图就明白了:
可以看到,这个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]));
}
蛮好玩的,大家可以将它扩展和增强一下,比如任何图片组合成文字(主要根据灰度),比如不只是一个字符,而是字符串(这个比上个要简单很多)。
作者:Sun.M
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.

浙公网安备 33010602011771号