在位图

时间:2017-07-17 03:05:11

标签: graphics bitmap mouseevent mousedown mouseup

我尝试使用鼠标向上鼠标向下鼠标在位图上绘制矩形。但问题是矩形总是延迟一个事件。例如,我尝试在第一次绘制一个矩形(0,0,50,50),但在位图上没有绘制矩形。我继续绘制一个矩形(50,50,100,100),但创建了一个矩形(0,0,50,50)(不是矩形(50,50,100,100)。如果我继续绘制下一个rects,它总是这样延迟。请帮忙我! 这是我的代码:

Rectangle rect = new Rectangle(0, 0, 0, 0);
int Xmouse;
int Ymouse;
public Form1()
{
    InitializeComponent();
    pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint);
      this.DoubleBuffered = true;
}

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    Xmouse = e.X;
    Ymouse = e.Y;
    drawOK = true;
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (drawOK)
    {
        drawOK = false;
        rect = new Rectangle(Xmouse * 3676 / 800, Ymouse * 3676 / 800, (e.X - Xmouse) * 3676 / 800, (e.Y - Ymouse) * 3676 / 800);
        pictureBox1.Invalidate();
    }

}


private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (var g = Graphics.FromImage(pictureBox1.Image))
    {
        using (Pen myPen = new Pen(Color.Black, 6))
        {
            g.DrawRectangle(myPen, rect);
        }
    }

}

1 个答案:

答案 0 :(得分:0)

尝试将绘制方法移出绘制到另一个子绘图中,然后从鼠标向上手动调用该子绘图:

Rectangle rect = new Rectangle(0, 0, 0, 0);
int Xmouse;
int Ymouse;
bool drawOK;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    Xmouse = e.X;
    Ymouse = e.Y;
    Console.WriteLine("MouseDown({0},{1})", e.X, e.Y);
    drawOK = true;
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (drawOK)
    {
        drawOK = false;
        Console.WriteLine("MouseUp({0},{1})", e.X, e.Y);
        rect = new Rectangle(Xmouse , Ymouse , (e.X - Xmouse) , (e.Y - Ymouse) );
        DrawRect();
        pictureBox1.Invalidate();
    }
}

private void DrawRect()
{
    Console.WriteLine("drawing {0}", rect);
    using (var g = Graphics.FromImage(pictureBox1.Image))
    {
        using (Pen myPen = new Pen(Color.Black, 6))
        {
            g.DrawRectangle(myPen, rect);
        }
    }
}

private void ClearPic()
{
    using (var g = Graphics.FromImage(pictureBox1.Image))
    {
        using (Brush myPen = Brushes.White)
        {
            g.Clear(Color.White);                 
        }
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    Image bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    pictureBox1.Image = bmp;
    ClearPic();
    pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint);
    pictureBox1.MouseDown += pictureBox1_MouseDown;
    pictureBox1.MouseUp += pictureBox1_MouseUp;
}