【发布时间】:2014-04-09 02:30:53
【问题描述】:
我有一些代码允许我(Windows 窗体)加载图像,在其上绘制一个矩形并保存它。但是我想实现“撤消”功能。如果我写一个矩形,我会在位图中绘制并保存修改后的位图。绘制另一个矩形后,我也保存位图(在列表中)。然而,我创建了一个按钮,删除我保存的最后一个位图,并将位图(新的最后一个)设置为图片框中的图像。那行得通,但是如果我做另一个矩形并单击撤消,则没有任何反应。我很困惑,不知道问题出在哪里。这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RecAngle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
Rectangle mRect;
Bitmap bm;
Image file;
Boolean opened = false;
SaveFileDialog sfd = new SaveFileDialog();
OpenFileDialog ofd = new OpenFileDialog();
Boolean draw = false;
List<Bitmap> bitMapList = new List<Bitmap>();
Boolean undo = false;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
mRect = new Rectangle(e.X, e.Y, 0, 0);
pictureBox1.Invalidate();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mRect = new Rectangle(mRect.Left, mRect.Top, e.X - mRect.Left, e.Y - mRect.Top);
pictureBox1.Invalidate();
draw = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
file = Image.FromFile(ofd.FileName);
bm = new Bitmap(ofd.FileName);
pictureBox1.Image = bm;
bitMapList.Add(bm);
opened = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult dr = sfd.ShowDialog();
if (opened)
{
try
{
bm.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception x)
{
Console.WriteLine(x);
}
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
try
{
if (draw)
{
if (undo)
{
bm = bitMapList[bitMapList.Count - 1];
}
using (Graphics a = Graphics.FromImage(bm))
{
Pen pen = new Pen(Color.Red, 2);
a.DrawRectangle(pen, mRect);
pictureBox1.Invalidate();
bitMapList.Add( new Bitmap(bm));
pictureBox1.Image = bitMapList[bitMapList.Count - 1];
}
}
}
catch (Exception x)
{
Console.WriteLine(x);
}
}
private void button3_Click(object sender, EventArgs e)
{
if (bitMapList.Count != 0)
{
bitMapList.RemoveAt(bitMapList.Count - 1);
pictureBox1.Image = bitMapList[bitMapList.Count - 1];
undo = true;
}
}
}
}
我保存的东西有错吗?我认为它与“删除”有关,但我真的没有看到错误。 谢谢你的帮助
【问题讨论】: