我试图编写一个输出给定文本块的PNG图像的代码。我使用System.Drawing
来实现这一目标。
我的问题是输出图像中的文字格式错误。
以下是我用来绘制输出的函数的代码:
static Bitmap FromTextToPic(string text, Int16 size)
{
//create dummy Bitmap object
Bitmap bitmapImage = new Bitmap(2, 2);
//create dummy measurements
int imageWidth = 0;
int imageHeight = 0;
//naming font
font = "Lohit-Devanagari";
// Creates the Font object for the image text drawing.
System.Drawing.Font fontObject = new System.Drawing.Font(font, size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
// Creates a graphics object to measure the text's width and height.
Graphics graphicsObject = Graphics.FromImage(bitmapImage);
// This is where the bitmap size is determined.
imageWidth = (int)graphicsObject.MeasureString(text, fontObject).Width;
imageHeight = (int)graphicsObject.MeasureString(text, fontObject).Height;
// Creates the bmpImage again with the correct size for the text and font.
bitmapImage = new Bitmap(bitmapImage, new Size(imageWidth, imageHeight));
// Adds the colors to the new bitmap.
graphicsObject = Graphics.FromImage(bitmapImage);
// Sets Background color to white
graphicsObject.Clear(System.Drawing.Color.White);
//enables optimization for LCD screens
graphicsObject.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//enables antialiasing
graphicsObject.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
//draws text to picture with black foreground color
graphicsObject.DrawString(text, fontObject, new SolidBrush(System.Drawing.Color.Black), 0, 0, StringFormat.GenericDefault);
graphicsObject.Flush();
return (bitmapImage);
}
即使我指定" Lohit-Devanagari"作为字体,我总是得到" Mangal"字体(都是梵文字体)。那么,我做错了什么?
此外,如果文本中没有换行符,则输出会延伸到很长的距离(如this picture中所示)。有没有办法将输出图像包装到某个固定宽度?
答案 0 :(得分:1)
而不是:
//naming font
font = "Lohit-Devanagari";
试试这个:
//naming font
FontFamily font = new FontFamily("Lohit Devanagari");
字体名称可能没有“ - ”字符。
如果声明一个新对象FontFamily,如果该字体不存在则会出现异常。所以你必须下载并安装它......