Z-Index of Drawing Rectangle C#

强颜欢笑 提交于 2019-12-25 02:24:04

问题


I have an application which uses the mouse to free-draw a rectangle on a picbox image. However the rectangle only shows up behind the picbox, rather than on top of it. Is there a property i can set which can fix this? (show rect on top of picbox image rather than behind it). Here is the code:

   System.Drawing.Graphics picboxGraphics;
    bool mDown = false;
    int mouseX;
    int mouseY;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        mDown = true;
        mouseX = e.X;
        mouseY = e.Y;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (mDown == true)
        {
            this.Refresh();
            Pen drawPen = new Pen(Color.Red, 5);
            int width = e.X - mouseX, height = e.Y - mouseY;
            Rectangle rect = new Rectangle(mouseX, mouseY, width * Math.Sign(width), height * Math.Sign(height));
            picboxGraphics = this.CreateGraphics();
            picboxGraphics.DrawRectangle(drawPen, rect);
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        mDown = false;
    }

回答1:


You creating graphics from form which is behind the picbox you can create graphics from picbox's image and draw someting. But if you want layer system you can draw your thins on an transparent image and combine them. with this vay you can make an undo or delete layer system.




回答2:


There are several problems in your code: dispose, global variable and wrong control to create graphics from. Make it this way:

using(var graphics = (sender as Control).CreateGraphics())
    graphics.DrawRectangle(drawPen, rect);

But honestly, you have to organize it differently (assuming you are going to mimik Paint):

  • create new object (when mouse is down)
  • in Paint event draw object (if any)
  • during mouse move event, update edited object properties and call Invalidate
  • when you minimize/restore your form, the object will be still there (while in your example, it will get lost).

You can support List of objects to have storage for many rectangles and add history support (as TC Alper Tokcan answer suggesting) to at least Undo last object.



来源:https://stackoverflow.com/questions/21677204/z-index-of-drawing-rectangle-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!