tags:

views:

4622

answers:

2

Hello,

I googled for "Drawing text on picturebox C#" ,but I couldnt find anything useful.Then I googled for "Drawing text on form C#" and I found some code,but it doesnt work the way I want it to work.

    private void DrawText()
    {
        Graphics grf = this.CreateGraphics();
        try
        {
            grf.Clear(Color.White);
            using (Font myFont = new Font("Arial", 14))
            {
                grf.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new PointF(2, 2));
            }
        }
        finally
        {
            grf.Dispose();
        }
    }

When I call the function,the background color of the form becomes white(it's black by default).

My questions:

1:Will this work on a picturebox?

2:How to fix the problem?

+6  A: 

You don't want that call to Clear() - that's why it's turning the background white, and it will cover up your picture.

You want to use the Paint event in the PictureBox. You get the graphics reference from e.Graphics, and then use the DrawString() that you have in your sample.

Here's a sample. Just add a picture box to your form, and add an event handler for the Paint event:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Font myFont = new Font("Arial", 14))
    {
        e.Graphics.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new Point(2, 2));
    }
}

(Note that you won't see the text at design time - you'll have to run the program for it to paint).

Jon B
I don't understand how to fix the problem.
John
Give me a few minutes and I'll post some sample code...
Jon B
+1; @John: just don't call Dispose of the e.Graphics object in the Paint event; you are only "borrowing" it.
Fredrik Mörk
Fredrik,Mork. I removed the using statement and the try statement aswell with the finally block ,but my background color still becomes white.
John
@John - the background is turning white because you're clearing it to white - just skip the Clear() call. See my edit - I added sample code.
Jon B
This also work is the user doesn't want the functionality of a label, and just wants to display text.
Malfist
Thanks,I would be even more thankful if you show me a way to set a label on a picturebox with transparent color(The answer below your answer).
John
@John - I've been down that road before. Windows doesn't work particularly well with true transparency. You get lots of flicker on the screen when it's resized. If you want to try it, the code in Malfist's link should do the trick.
Jon B
@John: here's another link for true transparency, might be a little more clear: http://www.c-sharpcorner.com/UploadFile/Nildo/NSA106032008213555PM/NSA1.aspx
Jon B
A: 

You have to create your own control and extend label, and set the background color as fully transparent.

Like here

Malfist