1
我正在嘗試編寫一個代碼,用於爲給定的文本塊輸出PNG圖像。我正在使用System.Drawing
來實現此目的。繪製圖像中的文本字體錯誤(C#)
我的問題是,輸出圖像中的文本是錯誤的字體。
下面是我使用,以得出輸出函數的代碼:
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);
}
即使當我指定「嘉黎,梵文」的字體,我總是得到輸出以「Mangal」字體(都是梵文字體)。那麼,我做錯了什麼?
此外,如果文本中沒有換行符(如this picture),則輸出延伸到很遠的距離。有沒有辦法將輸出圖像合併到某個固定的寬度?
非常感謝。解決了這個問題。 – roboPoco 2015-02-24 03:58:46