鼠标分层绘图问题-在已有的bmp图像上绘图
想在已有的bmp图像上用鼠标绘图,例如绘制一个矩形,就像photoshop中的选择工具一样,不知如何实现?我现在可以绘出矩形,但是覆盖了要编辑的图像,代码如下:
====================================
namespace WindowsApplication1
{
public partial class Form1 : Form
{
private string ChoFiNam;
Image Img = null;
private Size originalSize = new Size(0, 0);
Rectangle curRect;
double curZoom;
private bool IfMove;
private bool firstMove = true;
private Point StartPoint;
private Point EndPoint;
private Point MovingPoint;
public Form1()
{
InitializeComponent();
}
private void panel2_MouseDown(object sender, MouseEventArgs e)
{
IfMove = true;
StartPoint = new Point(e.X, e.Y);
}
private void panel2_MouseMove(object sender, MouseEventArgs e)
{
if (IfMove && e.Button == MouseButtons.Left)
{
if (firstMove)
{
firstMove = false;
EndPoint = new Point(e.X, e.Y);
Brush b = Brushes.Blue;
Pen p = new Pen(b);
DrawRect(p, StartPoint, EndPoint);
}
else
{
//通过利用新的颜色(背景色)重新绘制擦去先前已经画好的线
Color c = panel2.BackColor;
Pen p = new Pen(c);
DrawRect(p, StartPoint, EndPoint);
//画新的线
MovingPoint = new Point(e.X, e.Y);
Brush b = Brushes.Blue;
p = new Pen(b);
DrawRect(p, StartPoint, MovingPoint);
EndPoint = MovingPoint;
}
}
}
private void panel2_MouseUp(object sender, MouseEventArgs e)
{
//通过利用新的颜色(背景色)重新绘制擦去先前已经画好的线
Color c = panel2.BackColor;
//Brush b = Brushes.Blue;
Pen p = new Pen(c);
DrawRect(p, StartPoint, EndPoint);
}
private void DrawRect(Pen p, Point startPoint, Point endPoint)
{
Graphics g = panel2.CreateGraphics();
int Dwidth = Math.Abs((endPoint.X) - (startPoint.X));
int DHeight = Math.Abs((endPoint.Y) - (startPoint.Y));
//g.DrawLine(p, startPoint, endPoint);
g.DrawRectangle(p, startPoint.X, startPoint.Y, Dwidth, DHeight);
}
private void segButton2_Click(object sender, EventArgs e) // 选择要编辑的图像
{
if (opFiDg2.ShowDialog() == DialogResult.OK)
{
ChoFiNam = opFiDg2.FileName;
curZoom = 1.0; // 初始值;
try
{
Img = Image.FromFile(ChoFiNam);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
panel2.AutoScrollMinSize = new Size
((int)(Img.Width),
(int)(Img.Height));
curRect = new Rectangle(0, 0, Img.Width, Img.Height);
panel2.Invalidate();
// Save origianl size of the imageOrWth, OrHit;
originalSize.Width = Img.Width;
originalSize.Height = Img.Height;
}
}
private void panel2_Paint(object sender, PaintEventArgs e)// 绘制bmp图像
{
Graphics g = e.Graphics;
if (Img != null)
{
g.DrawImage(Img, new Rectangle
(panel2.AutoScrollPosition.X,
panel2.AutoScrollPosition.Y,
(int)(curRect.Width * curZoom),
(int)(curRect.Height * curZoom)));
}
}
}
}