我正在使用以下代码将文本绘制到位图上:
GraphicsPath pth = new GraphicsPath();
var style = (int)myfont.Style;
pth.AddString(tcaption.Text, myfont.FontFamily, style, myfont.Size, point, StringFormat.GenericTypographic);
p = new Pen(new SolidBrush(bc), 2f);
mygraphics.DrawPath(p, pth);
我正在使用
TextRenderer
来测量字符串的大小。int Width = TextRenderer.MeasureText(tcaption.Text, myfont).Width;
但是这样并不能产生正确大小的绘制字符串;实际绘制字符串的大小与所需大小相差约20-30%?
我做错了什么?请给予建议。
更新:
我想在位图上绘制文本和图像,为了容纳两者,我创建了一个如下的位图:
intWidth = TextRenderer.MeasureText(tcaption.Text, cfont).Width + image.Width;
intHeight = TextRenderer.MeasureText(tcaption.Text, cfont).Height +image.Height;
tempimage= new Bitmap(intWidth, intHeight);
然后,我从位图中创建了Graphics对象,如下所示:
using (Graphics newg = Graphics.FromImage(tempimage))
@Hans Passant
我也尝试过Graphics.MeasureString
作为TextRenderer的替代方案。
现在,我已经设置了文本和图像的位置 - 我需要将图像绘制在左上角。
imageposy = 0;
imageposx = 10;
textposy = image.Height;
textposx = 0;
然后我像这样绘制文本。
po=new Point(textposx, textposy);
newg.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath pth = new GraphicsPath();
var style = (int)myfont.Style;
pth.AddString(tcaption.Text, myfont.FontFamily, style, myfont.Size, po,
StringFormat.GenericTypographic);
newg.FillPath(new SolidBrush(fc), pth);
现在我像这样绘制图像。
Rectangle nrect = new Rectangle(imageposx, imageposy, image.Width,
image.Height);
objGraphics = Graphics.FromImage(tempimage);
objGraphics.DrawImage(image, nrect);
正如您所看到的,我需要将偏移量10
添加到图像位置的x坐标上以纠正测量问题。
希望我的更新能更好地解决问题...我错在哪里了?请给予建议...
MeasureText
方法要求文本在单行上绘制。所以如果tcaption.Text
是多行的,那可能会有关系?不过我对TextRenderer
对象并不是很熟悉。 - sab669