1

I'm drawing a String with g.DrawString on an image. Before I'm doing this I'm also drawing images on the source image.

This is what my code looks like:

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);

That's what I get: enter image description here

If I now add these two lines before the already mentioned code like this:

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);

I get this: enter image description here

I didn't change anything besides these two lines. So my question is how is this happening.

1
  • 1
    Well wherre is g coming from in the first version? Commented Jan 31, 2012 at 18:49

1 Answer 1

1

Check the DPI of the source PNG. When you load a Bitmap from file, it loads the DPI that was recorded in the file. When you create a new Bitmap based on another Bitmap that's already in memory, it resets it to the screen DPI. It does not carry over the original DPI setting.

You can specify that your font be represented with GraphicsUnit.Pixel like this:

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

Otherwise your font will scale with the DPI of the image. Image DPI is just used to define how large in real-world units (inches) the image is supposed to be. You may or may not want to use that information when scaling your text, depending on if you're scaling it for print.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.