奇怪的DrawString行为

时间:2012-01-31 18:46:36

标签: c# graphics bitmap

我在图片上绘制了一个带g.DrawString的字符串。在我这样做之前,我还在源图像上绘制图像。

这就是我的代码:

Bitmap sourceBitmap = Image.FromFile(myBitmap) as Bitmap;
Graphics g = Graphics.FromImage(sourceBitmap);

// drawing some other images on sourceBitmap with g.DrawImage

int positionx = 100;
Font ftemp = cvt.ConvertFromString(myfont) as Font; // predefined font
SizeF mysize = TextRenderer.MeasureText(mytext, ftemp); 
PointF myposition = new PointF(positionx - mysize.Width, positiony) // align right
g.DrawString(mytext, ftemp, new SolidBrush(mycolor), myposition);

这就是我得到的:enter image description here

如果我现在在已提到的代码之前添加这两行,如下所示:

Bitmap sourceBitmap = Image.FromFile(myBitmap) as Bitmap;
Graphics g = Graphics.FromImage(sourceBitmap);

// drawing some other images on sourceBitmap with g.DrawImage

sourceBitmap = new Bitmap(sourceBitmap); // sourceBitmap is the bitmap (png) I'm drawing on from the very beginning.
g = Graphics.FromImage((Image)sourceBitmap);

int positionx = 100;
Font ftemp = cvt.ConvertFromString(myfont) as Font; // predefined font
SizeF mysize = TextRenderer.MeasureText(mytext, ftemp); 
PointF myposition = new PointF(positionx - mysize.Width, positiony) // align right
g.DrawString(mytext, ftemp, new SolidBrush(mycolor), myposition);

我明白了:enter image description here

除了这两行之外,我没有改变任何东西。所以我的问题是这是怎么回事。

1 个答案:

答案 0 :(得分:1)

检查源PNG的DPI。从文件加载位图时,它会加载文件中记录的DPI。当您基于已经在内存中的另一个位图创建新的位图时,它会将其重置为屏幕DPI。它不会延续原始的DPI设置。

您可以指定使用GraphicsUnit.Pixel表示您的字体,如下所示:

Font f = new Font("Arial", 10.0f, GraphicsUnit.Pixel);

否则,您的字体将随图像的DPI缩放。图像DPI仅用于定义图像的实际单位(英寸)的大小。在缩放文本时,您可能希望也可能不希望使用该信息,具体取决于您是否将其缩放以进行打印。