C#中使用DrawString绘制文本时怎样使文本居中或右对齐
asp.net C#中使用DrawString绘制文本时怎样使文本居中或右对齐
string _FontName = "UKK TZA1";
int _FontSize = 30;
string txt = TextBox1.Text;
txt = HtmlCode(TextBox1.Text);
string _ShowName = txt;
Bitmap objBitmap = null;
Graphics g = null;
Font stringFont = new Font(_FontName, _FontSize, FontStyle.Bold);
//StringFormat stringFormat = new StringFormat();
//stringFormat.FormatFlags = StringFormatFlags.NoWrap;
//stringFormat.Alignment = StringAlignment.Center;
try
{
StringFormat format = new StringFormat(StringFormatFlags.DirectionRightToLeft);
objBitmap = new Bitmap(1, 1);
g = Graphics.FromImage(objBitmap);
SizeF stringSize = g.MeasureString(_ShowName, stringFont, 500, format);
int nWidth = (int)stringSize.Width;
int nHeight = (int)stringSize.Height;
g.Dispose();
objBitmap.Dispose();
objBitmap = new Bitmap(nWidth, nHeight);
g = Graphics.FromImage(objBitmap);
g.FillRectangle(new SolidBrush(Color.LightSkyBlue), new Rectangle(0, 0, nWidth, nHeight));
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.DrawString(_ShowName, stringFont, new SolidBrush(Color.Black), new PointF(0, 0), format);
objBitmap.Save(@"d:\test.gif", ImageFormat.Gif);
}
catch (Exception ee)
{
Response.Write(ee.ToString());
}
finally
{
if (null != g) g.Dispose();
if (null != objBitmap) objBitmap.Dispose();
Response.End();
}
这是我的代码,正常运行,但结果绘出来的文字总是 左对齐,有什么办法使文字右对齐或居中?