简体   繁体   中英

How to draw border for panel which is continously resizing c#

Using panel as a selection indicator . The panel changes its size according to cursor position on MouseMove event . However when I draw the border as below , previous borders leave their mark on the panel and it displays too many border within same panel . Even tried refresh() before every draw but that makes it glitchy and slow

private void panel1_Paint(object sender, PaintEventArgs e)
{
    this.panel1.Refresh();
    ControlPaint.DrawBorder(e.Graphics, this.panel1.ClientRectangle, Color.DarkBlue, ButtonBorderStyle.Solid);
}

private void drawboard_MouseMove(object sender, MouseEventArgs e)
{
    panel1.Width = e.Location.X - panel1.Left;
    panel1.Height = e.Location.Y - panel1.Top;        
}

First off, you should never call control paint affecting methods like Invalidate or Refresh inside the control paint handler.

You can solve the original issue by calling Invalidate or Refresh after modifying the size of the panel. Note that it's better to set the Size property with one call rather than Width and Height separately:

private void panel1_Paint(object sender, PaintEventArgs e)
{
    ControlPaint.DrawBorder(e.Graphics, this.panel1.ClientRectangle, Color.DarkBlue, ButtonBorderStyle.Solid);
}

private void drawboard_MouseMove(object sender, MouseEventArgs e)
{
    var size = new Size(Math.Max(e.Location.X - panel1.Left, 0), 
        Math.Max(e.Location.Y - panel1.Top, 0));
    if (panel1.Size != size)
    {
        panel1.Size = size;
        panel1.Invalidate();
    }
}

A better option is to set ResizeRedraw property of the selection panel to true . Since it's a protected property, you need to create and use your own Panel subclass. As a bonus, you can also set DoubleBuffered property to true to avoid the flickering, and also move the painting code inside:

class SelectionBox : Panel
{
    public SelectionBox()
    {
        ResizeRedraw = true;
        DoubleBuffered = true;
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Color.DarkBlue, ButtonBorderStyle.Solid);
    }
}

Make your panel1 to be SelectionBox , remove the Paint event handler, and then the mouse move handler could be simple

private void drawboard_MouseMove(object sender, MouseEventArgs e)
{
    panel1.Size = new Size(Math.Max(e.Location.X - panel1.Left, 0), 
        Math.Max(e.Location.Y - panel1.Top, 0));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM