开发者

C# drawing issue

I have a general question about drawing in C#. In a class Test I have a method Draw:

public void Draw(Graphics g)
    {
        g.DrawLine(Pens.Black, x1, y1, x2, y2);
    }

And now I want to draw it in my Main Form in a Picturebox called PictureBox1

But how can I draw it?

Normally you can draw in a picturebox like this:

private void Draw()
{
   Graphics g = PictureBox1.CreateGraphics();
   g.DrawLine(Pens.Black, x1, y1, x2, y2);
}

I know it is a silly question, but I am a beginner and want to get the basics ;)

best wishes :)

EDIT:

Sorry, i don't understand your postings at all, can you explain it to me again

EDIT 2:

Thanks for your answers. But I don't know how this works.

There is my class Test and in this class there is the Draw Method:开发者_Python百科

private void Draw()
{
   Graphics g = PictureBox1.CreateGraphics();
   g.DrawLine(Pens.Black, x1, y1, x2, y2);
}

Now I want to draw this methode in my PictureBox which is in my MainClass FormMain

how can i draw test.Draw() in my picturbox which is in a other class?

I hope now it is clear and sorry for my inexperience best wishes


The picturebox control will overwrite whatever is on it each time the paint event gets fired (which is pretty much all the time). So you need to wire into that event:

this.pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint);

Then in the event do your drawing:

void pictureBox1_Paint(object sender, PaintEventArgs e)
{
     // Assuming your constructor takes coordinates as parameters
     var t = new Test(0, 0, 100, 100);
     t.Draw(e.Graphics);
}


You have to create the Graphics object from a Control object.

For instance:

override void myControl OnPaint (PaintEventArgs e)
{
    Graphics g = e.Graphics

    //do something with g
}

I can probably provide better information with a little bit of guidance on what you expect the custom class Test to accomplish.


There are a few ways to do this:

  1. You could create an event in your Test class and subscribe to the event in your form. Then, you can call PictureBox1.CreateGraphics() without problem.
  2. You could pass the current instance of your form to a method in your Test class and refer to the PictureBox via the instance you passed in to the method.


The PictureBox control is designed to hold an image inside. What you need to do is paint on this image, then you won't have to mess with paint events. Like that:

var img = new Bitmap();
using (Graphics g = Graphics.FromImage(img)) {
    g.DrawLine(Pens.Black, x1, y1, x2, y2);
}
pictureBox1.Image = img;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜