【发布时间】:2023-04-10 02:00:01
【问题描述】:
目标:
在松开鼠标左键时绘制一个红色矩形。保留矩形。
代码:
private void button1_Click(object sender, EventArgs e)
{
if (Clipboard.ContainsImage())
{
pictureBox1.Image?.Dispose();
pictureBox1.Image = Clipboard.GetImage();
}
else
{
MessageBox.Show("No Image detected in clipboard." + Environment.NewLine + "Have you print screened the label?", "Print Screen", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
LocationXY = e.Location;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
LocationX1Y1 = e.Location;
pictureBox1.Invalidate();
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
LocationX1Y1 = e.Location;
pictureBox1.Invalidate();
pictureBox2.Invalidate();
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (MouseButtons == MouseButtons.Left)
{
e.Graphics.DrawRectangle(Pens.Red, GetRect());
}
}
private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
var src = GetRect();
if (src == Rectangle.Empty) return;
var des = new Rectangle(0, 0, src.Width, src.Height);
e.Graphics.DrawImage(pictureBox1.Image,
des, src, GraphicsUnit.Pixel);
}
private Rectangle GetRect()
{
return new Rectangle(
Math.Min(LocationXY.X, LocationX1Y1.X),
Math.Min(LocationXY.Y, LocationX1Y1.Y),
Math.Abs(LocationXY.X - LocationX1Y1.X),
Math.Abs(LocationXY.Y - LocationX1Y1.Y)
);
}
private Bitmap GetCroppedImage()
{
var des = GetRect();
if (des == Rectangle.Empty) return null;
var b = new Bitmap(des.Width, des.Height);
using (var g = Graphics.FromImage(b))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, des.Width, des.Height), des, GraphicsUnit.Pixel);
}
return b;
}
结果:
点击一个按钮,这个打印的屏幕图像就会显示出来:
[![在此处输入图片描述][1]][1]
如果我使用鼠标左键单击并拖动,会出现这个红色矩形:
[![在此处输入图片描述][2]][2]
我一发布:
[![在此处输入图片描述][1]][1]
问题:
如何标记要裁剪的区域并将红色矩形保留在那里?没有消失
【问题讨论】:
标签: c#