首先,我很抱歉我的英语不好。现在我遇到了我的C#项目(ms paint)的问题。当我在图片框中打开新图片时,我绘制的最后一个图形仍然保留,直到我在此图像上绘制另一条线。这是我的代码:
- 画线:
public Form1()
{
InitializeComponent();
snapshot = new Bitmap(pictureBox1.Width, pictureBox1.Height);
}
if (tempDraw != null)
{
tempDraw = (Bitmap)snapshot.Clone();
Graphics g = Graphics.FromImage(tempDraw);
Pen myPen = new Pen(colorPickerDropDown1.SelectedColor, 5);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
myPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
g.DrawLine(myPen, pDau, pHientai);
myPen.Dispose();
e.Graphics.DrawImageUnscaled(tempDraw, 0, 0);
g.Dispose();
}
- 鼠标事件:
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
paint = false;
snapshot = (Bitmap)tempDraw.Clone();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
paint = true;
saved = false;
pDau = e.Location;
tempDraw = (Bitmap)snapshot.Clone();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (paint)
{
pHientai = e.Location;
pictureBox1.Invalidate();
saved = false;
}
}
- 创建新图片框:
public void New()
{
pictureBox1.Image =null;
snapshot = null;
tempDraw = null;
snapshot= new Bitmap(pictureBox1.Width, pictureBox1.Height);
}
- 打开图片:
New();
snapshot = new Bitmap(openFileDialog1.FileName);
tempDraw = (Bitmap)snapshot.Clone();
pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
strPath = openFileDialog1.FileName;
this.Text = strPath + " - Paint";
你能告诉我一些错事吗?非常感谢你!
答案 0 :(得分:0)
在您的第一个代码示例中,我是否正确假设整个if
语句实际上位于表单的Paint
事件中?像这样:
private void Form_Paint(object sender, PaintEventArgs e)
{
if (tempDraw != null)
{
tempDraw = (Bitmap)snapshot.Clone();
Graphics g = Graphics.FromImage(tempDraw);
Pen myPen = new Pen(colorPickerDropDown1.SelectedColor, 5);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
myPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
g.DrawLine(myPen, pDau, pHientai);
myPen.Dispose();
e.Graphics.DrawImageUnscaled(tempDraw, 0, 0);
g.Dispose();
}
}
如果是这样,请考虑调用e.Graphics.Clear(this.BackColor)
以使用自己的背景颜色清除表单。这将有效地删除您绘制的任何内容。另外,在创建绘图对象时,请考虑using
语句,以便在任何方法抛出异常时保护您。我会像这样重写你的if
语句:
if (tempDraw != null)
{
tempDraw = (Bitmap)snapshot.Clone();
using (Graphics g = Graphics.FromImage(tempDraw))
using (Pen myPen = new Pen(colorPickerDropDown1.SelectedColor, 5))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
myPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
g.DrawLine(myPen, pDau, pHientai);
e.Graphics.Clear(this.BackColor); // clear any drawing on the form
e.Graphics.DrawImageUnscaled(tempDraw, 0, 0);
}
}