绘图矩形C#的Z索引 [英] Z-Index of Drawing Rectangle C#

查看:79
本文介绍了绘图矩形C#的Z索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用鼠标在picbox图片上自由绘制矩形的应用程序.但是,矩形仅显示在picbox的后面,而不是在其顶部.我可以设置可以解决此问题的属性吗? (将rect显示在picbox图像的顶部,而不是在其后面).这是代码:

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;
    }

推荐答案

您的代码中存在几个问题:处置,全局变量和从中创建图形的错误控制.做到这一点:

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);

但是说实话,您必须以不同的方式组织它(假设您要使用mimik Paint):

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

  • 创建新对象(鼠标按下时)
  • Paint事件绘制对象中(如果有)
  • 在鼠标移动事件期间,更新已编辑对象的属性并调用Invalidate
  • 最小化/还原表单时,对象将仍然存在(在您的示例中,它将丢失).
  • 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).

您可以支持List个对象以存储许多矩形,并至少对Undo个最后一个对象添加历史记录支持(如TC Alper Tokcan所建议的那样).

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.

这篇关于绘图矩形C#的Z索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆