-1

我正在使用以下代码进行绘制。我不知道为什么要这样做。在它工作正常之前。当我添加“picBox.Image = new Bitmap(560, 464);”时 我的 form() 中的这一行,我添加了这个 Graphics.FromImage(picBox.Image)...

private void picBox_MouseDown(object sender, MouseEventArgs e)
    {

        draw = true;
        x = e.X;
        y = e.Y;

    }

private void picBox_MouseMove(object sender, MouseEventArgs e)
        {


            if (draw)
            {
                //Graphics g = picBox.CreateGraphics();
                switch (currItem)
                {
                    case Item.Rectangle:
                        Graphics.FromImage(picBox.Image).FillRectangle(new SolidBrush(paintColor), x, y, e.X - x, e.Y - y);
                        break;
                    case Item.Ellipse:
                        Graphics.FromImage(picBox.Image).FillEllipse(new SolidBrush(paintColor), x, y, e.X - x, e.Y - y);
                        break;           

                }
                picBox.Refresh();
                Graphics.FromImage(picBox.Image).Dispose();
            }
        }
 private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        draw = false;
        lx = e.X;
        ly = e.Y;


    }
4

1 回答 1

0

您正在Graphics使用对图像执行的每个操作创建一个对象。还要看看你需要在图像的正确位置绘制的数学,因为你正在使用PictureBoxSizeMode.StretchImage

尝试这个:

Graphics g;
private void picBox_MouseDown(object sender, MouseEventArgs e)
{
    g = Graphics.FromImage(picBox.Image);
    draw = true;
    x = e.X;
    y = e.Y;

}

private void picBox_MouseMove(object sender, MouseEventArgs e)
{
    if (draw)
    {
        // since you are using PictureBoxSizeMode.StretchImage:
        float rescaleX = (float)pixBox.Image.Width / pixBox.Width;
        float rescaleY = (float)pixBox.Image.Height / pixBox.Height;

        // if you do not want to produce a "trail" of shapes
        g.Clear(picBox.BackColor);
        switch (currItem)
        {
            case Item.Rectangle:
                g.FillRectangle(new SolidBrush(paintColor), 
                          x * rescaleX, 
                          y * rescaleY, 
                          (e.X - x) * rescaleX, 
                          (e.Y - y) * rescaleY);
                break;
            case Item.Ellipse:
                g.FillEllipse(new SolidBrush(paintColor), 
                          x * rescaleX, 
                          y * rescaleY, 
                          (e.X - x) * rescaleX, 
                          (e.Y - y) * rescaleY);
                break;           
        }
        picBox.Refresh();
    }
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    draw = false;
    lx = e.X;
    ly = e.Y;

    g.Dispose();
}

但是,如果这应该成为某种简单的绘画,您将需要更多的逻辑:只要鼠标按下,在您在图像上方绘制的一些临时缓冲区中绘制。释放鼠标按钮后,“提交”此缓冲区(通过将其绘制在图像顶​​部)。

于 2013-09-16T13:41:22.483 回答