form1 top
Rectangle rect;
bool painting = false;
构造
this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1 mousedown事件
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
rect = new Rectangle(e.X, e.Y, 0, 0);
painting = true;
}
}
picturebox1 mousemove事件
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
rect = new Rectangle(rect.Left, rect.Top, Math.Min(e.X - rect.Left, pictureBox1.ClientRectangle.Width - rect.Left), Math.Min(e.Y - rect.Top, pictureBox1.ClientRectangle.Height - rect.Top));
}
this.pictureBox1.Invalidate();
}
picturebox1绘制事件
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (painting == true)
{
using (Pen pen = new Pen(Color.Red, 2))
{
e.Graphics.DrawRectangle(pen, rect);
}
}
}
picturebox1 mouseup
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
timer1.Enabled = false;
Image tmp = pictureBox1.Image;
pictureBox1.Image = SaveRectanglePart(pictureBox1.Image, rect);
if (tmp != null)
tmp.Dispose();
}
方法SaveRectaglePart
public Bitmap SaveRectanglePart(Image image, RectangleF sourceRect)
{
var bmp = new Bitmap((int)sourceRect.Width, (int)sourceRect.Height);
using (var graphics = Graphics.FromImage(bmp))
{
graphics.DrawImage(image, 0.0f, 0.0f, sourceRect, GraphicsUnit.Pixel);
}
return bmp;
}
问题是当我在pictureBox1上绘制一个矩形然后当它在鼠标向上事件时我想要它做的是将picturebox1中的当前图像替换为矩形内的图像我drawed。
在绘制的矩形中拉伸图像并将其分配给pictureBox1,现在在pictureBox1中我将从绘制的矩形内部获得裁剪后的图像。
但我在pictureBox1中获得的内容是放大了图片。无法弄清楚原因。
这是我绘制矩形时的截图
这是我在mouseup事件中获得的截图。