Reputation: 139
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:
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
Upvotes: 0
Views: 2227
Reputation: 12381
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;
Upvotes: 0
Reputation: 999
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);
}
Upvotes: 2
Reputation: 167
There are a few ways to do this:
Upvotes: 0
Reputation: 19881
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.
Upvotes: 0