用刷子在现有图像上涂漆



我已经在一个项目中嵌入了下面的代码,其中想要用刷子在图片上绘画。问题是,如果为主面板编写此代码,一切都很好,但是由于我想将其用于现有图像,所以我看不到刷子。我想刷子是涂料,但它是前景/背景的问题。

//the first line goes to the main form  - under the initialize component
graphics = DisplayPicturebox.CreateGraphics();
bool draw = false;
Graphics graphics;
private void DisplayPicturebox_MouseDown(object sender, MouseEventArgs e)
{
    draw = true;
}
private void DisplayPicturebox_MouseUp(object sender, MouseEventArgs e)
{
    draw = false;
}
private void DisplayPicturebox_MouseMove(object sender, MouseEventArgs e)
{
    if (draw)
    {
        //create a brush:
        SolidBrush MysolidBrush = new SolidBrush(Color.Red);
        graphics.FillEllipse(MysolidBrush, e.X, e.Y,
                      Convert.ToInt32(toolStripTextBox1.Text),
                      Convert.ToInt32(toolStripTextBox1.Text));
    }
}

这里要注意的一些重要事项:

  • 需要在管道中处理图形以某种方式保存,以便重新粉刷不会消除用户所做的更改。

  • 无限期地保持图形上下文是一个坏主意。您应该足够打开上下文日志,以绘制您需要的内容,要么将其绘制到缓冲区或屏幕上,然后关闭该上下文。

  • 如果要使用屏幕外缓冲区,则需要记住您正在工作的坐标系("屏幕" v vess'v vess" control",而不是"缓冲区")。如果您感到困惑,您可能看不到您的期望

考虑到这些概念,您可以考虑对代码的以下更改:

// at the beginning of your class declare an offscreen buffer
private System.Drawing.Bitmap buffer;
// .. later create it in the constructor
public Form1() {
  InitializeComponent();
  // use the w/h of the picture box here
  buffer = new System.Drawing.Bitmap(picBox.Width, picBox.Height);
}
// in the designer add a paint event for the picture box:
private picBox_Paint(object sender, System.Windows.Forms.PaintEventArgs e) {
   e.Graphics.DrawImageUnscaled(buffer);
}
// finally, your slightly modified painting routine...
private picBox__MouseMove(object sender, MouseEventArgs e)
{
  if (draw)
  {
    using (var context = System.Drawing.Graphics.FromImage(buffer)) {
      //create a brush:
      SolidBrush MysolidBrush = new SolidBrush(Color.Red);
      graphics.FillEllipse(MysolidBrush, e.X, e.Y,
                    Convert.ToInt32(toolStripTextBox1.Text),
                    Convert.ToInt32(toolStripTextBox1.Text));
    }
  }
}

这并不是要成为完美的代码,但是一般模板应该有效,并使您更接近我所寻找的内容。希望对某些有帮助!

尝试此操作,修改Mousemove事件:

private void DisplayPicturebox_MouseMove(object sender, MouseEventArgs e)
    {
        if (draw)
        {
            graphics = DisplayPicturebox.CreateGraphics();
            SolidBrush MysolidBrush = new SolidBrush(Color.Red);
            float newX = (float)DisplayPicturebox.Image.Size.Width / (float)DisplayPicturebox.Size.Width;
            float newY = (float)DisplayPicturebox.Image.Size.Height / (float)DisplayPicturebox.Size.Height;
            graphics = Graphics.FromImage(DisplayPicturebox.Image);
            graphics.FillEllipse(MysolidBrush, e.X * newX, e.Y * newY, Convert.ToInt32(toolStripTextBox1.Text), Convert.ToInt32(toolStripTextBox1.Text));
            DisplayPicturebox.Refresh();
        }
    }

相关内容

  • 没有找到相关文章

最新更新