hivokas
hivokas

Reputation: 71

How can I draw from another class?

I have MainForm class. Here I can make somthing like this.

private void MainForm_Paint(object sender, PaintEventArgs e)
{
    Graphics graphics = this.CreateGraphics();
    Rectangle rectangle = new Rectangle(50, 100, 150, 150);
    graphics.DrawEllipse(Pens.Black, rectangle);
    graphics.DrawRectangle(Pens.Red, rectangle);
}

And I can see result in my Form.

But I have another class Image. And I want to draw from here. How can I do it?

Upvotes: 2

Views: 1834

Answers (1)

ferday
ferday

Reputation: 197

Send the PaintEventArgs (the below came from one i have been using)

class Draw
{
    public void Paint(PaintEventArgs e)
    {
          e.Graphics.DrawRectangles(Pens.Blue, GetRectangle());                        
    }
}

where GetRectangle would be another method to define the rectangle

you should also be able to just send your object (in your case the instance of MainForm)

class Draw
{
    public void Paint(MainForm main)
    {
        Graphics graphics = main.CreateGraphics();
    }
}

or the graphics object

class Draw
{
    public void Paint(Graphics graphics)
    {
        Rectangle rectangle = new Rectangle(50, 100, 150, 150);
        graphics.DrawEllipse(Pens.Black, rectangle);
        graphics.DrawRectangle(Pens.Red, rectangle);
    }
}

you still need the event handler for the PictureBox, so you would do something like

private void MainForm_Paint(object sender, PaintEventArgs e)
{
    Graphics graphics = this.CreateGraphics();
    Draw image = new Draw();
    image.Paint(graphics);
}

Upvotes: 3

Related Questions