sara sara - 26 days ago 19
C# Question

Painting a rectangle

I'm very new to windows form coding and I'm trying to make a minipaint which has three buttons (circle,rectangle and line) and when it gets a button as an input , it will draw the shape in panel.
I have this shape class

class shape
{
public Color color { get; set; }
public int width { get; set; }
public int startx { get; set; }
public int starty { get; set; }
}


which has color,width and start position properties.then I have this rectangle class for example:

class rectangle : shape
{
int length { get; set; }
int width { get; set; }
}


which inherits the share properties from the shape class. now I want to print a rectangle in panel . I'm familiar with
DrawRectangle
method and I printed a rectangle as bellow:

Pen black = new Pen(Color.Black);
Rectangle rect = new Rectangle(20,20,400,200);
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawRectangle(black, rect);
}


but I don't know how to draw a rectangle from
class rectangle:shape
. I'm also having problem with assigning value from click button to rectangle.
can you please help me?

Answer

May I suggest you have one draw function in your base class that each shape overrides.

class shape
{
    public Color color { get; set; }
    public int width { get; set; }
    public int startx { get; set; }
    public int starty { get; set; }

    public virtual void Draw(Graphics g)
    {
    }
}

class rectangle : shape
{
    int length { get; set; }
    int width { get; set; }

    public override void Draw(Graphics g)
    {
        using (Pen pen = new Pen(color))
        {
            g.DrawRectangle(pen, new Rectangle(startx, starty, width, length));
        }
    }
}

Then any shape can be drawn by calling .Draw(graphics).

Comments