C#剪切问题
/// <summary>/// 剪切图片的按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnShear_Click(object sender, EventArgs e)
{
b = true;
}
/// <summary>
/// 获取按下鼠标指针的坐标
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
if (b)
{
this.Cursor = Cursors.Cross;
p1 = new Point(e.X, e.Y);
}
}
/// <summary>
/// 记录鼠标的移动
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (b)
{
if (this.Cursor == Cursors.Cross)
{
p2 = new Point(e.X, e.Y);
pictureBox.Invalidate();
}
}
}
/// <summary>
/// 获取松开鼠标时指针的坐标
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
if (b)
{
this.Cursor = Cursors.Default;
p2 = new Point(e.X, e.Y);
CutImage();
b = false;
}
}
/// <summary>
/// 记录鼠标在PictureBox上面画的矩形
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBox_Paint(object sender, PaintEventArgs e)
{
if (b)
{
Pen p = new Pen(Color.White, 1);
p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
Rectangle rect = new Rectangle(p1, new Size(p2.X-p1.X,p2.Y-p1.Y));
e.Graphics.DrawRectangle(p, rect);
p.Dispose();
}
}
/// <summary>
/// 剪切图片
/// </summary>
private void CutImage()
{
try
{
img = this.pictureBox.Image;
bt1 = new Bitmap(p2.X - p1.X, p2.Y - p1.Y);
Rectangle tgtRect = new Rectangle(0, 0, p2.X - p1.X, p2.Y - p1.Y);
Rectangle srcRect = new Rectangle(p1.X, p1.Y, p2.X - p1.X, p2.Y - p1.Y);
Graphics g = Graphics.FromImage(bt1);
g.DrawImage(img, tgtRect, srcRect, GraphicsUnit.Pixel);
this.pictureBox.Image = bt1;
g.Dispose();
pictureBox.Refresh();
}
catch(Exception)
{
}
}
剪切跑位怎么处理啊?