Click here to Skip to main content
15,867,999 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying do generate a kind of background picture containing graphics and text. With graphics I didn't encounter any problems so far. But there is a problem with text. If I write normal text into a bitmap the characters look like blurred bold characters. If I write directly into the form everything is as expected.

using System.Drawing;
using System.Windows.Forms;

namespace Bitmap_test
{
    public partial class Form1 : Form
    {
        readonly Font textFont;
        
        public Form1()
        {
            InitializeComponent();
            textFont = new Font("Microsoft Sans Serif", 9F);
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Bitmap myBitmap = new Bitmap(300, 100, e.Graphics); // new Bitmap(300, 100) makes no difference
            using (Graphics g = Graphics.FromImage(myBitmap))
            {
                g.DrawString("Test", textFont, Brushes.Black, 10, 20);    // Characters look like blurred bold characters.
            }

            e.Graphics.DrawImage(myBitmap, new Point(0, 0)); // Draw the bitmap containing the text
            e.Graphics.DrawString("Test", textFont, Brushes.Black, 10, 50); // Characters look like expected
        }

What's the problem and how can I solve It.

What I have tried:

Experimented with the creation of the bitmap (with / without the third argument).
Posted
Updated 5-Jun-21 3:27am

Try this:
C#
Bitmap myBitmap = new Bitmap(300, 100, e.Graphics);

using (Graphics g = Graphics.FromImage(myBitmap))
    {
    g.Clear(Color.White);
    g.DrawString("Test", textFont, Brushes.Black, 10, 20);    // Characters look like blurred bold characters.
    }
e.Graphics.DrawImage(myBitmap, new Point(0, 0)); // Draw the bitmap containing the text
e.Graphics.DrawString("Test", textFont, Brushes.Black, 10, 50); // Characters look like expected
 
Share this answer
 
I modified your suggestion and replaced
g.Clear(Color.White);
by
g.Clear(BackColor);

That seems to work. But I don't understand why.
 
Share this answer
 
v2
Comments
OriginalGriff 5-Jun-21 10:02am    
To be honest, I'm not sure either - just I've met it before.
I think - and that's all - that it's to do with an empty bitmap being initialized to zeros: which is "all black with zero alpha channel" and you drawing with black on that (which presumably has a solid alpha but I haven't checked). I'm guessing that the fuzzyness is antialiasing of the font combining with the alpha.

I do know that clearing the bitmap is the first thing I do once I've created one! :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900