// 根據鼠標位置計算並繪製選區矩形
private void DrawRect(Graphics painter, int mouseX, int mouseY)
{
int width = 0, height = 0;
// Y 方向
if (mouseY < Rect.Y)
{
Rect.Y = mouseY;
height = downPoint.Y - mouseY;
}
else height = mouseY - downPoint.Y;
// X 方向
if (mouseX < Rect.X)
{
Rect.X = mouseX;
width = downPoint.X - mouseX;
}
else width = mouseX - downPoint.X;
Rect.Size = new Size(width, height);
painter.DrawRectangle(pen, Rect);
}
// 克隆背景並繪製選區,返回新圖像
private Image DrawScreen(Image background, int mouseX, int mouseY)
{
using (Graphics g = Graphics.FromImage(background))
{
DrawRect(g, mouseX, mouseY);
}
return background;
}
// 移動選區並刷新顯示
private void MoveRect(Image baseImage, Rectangle rect)
{
using (Graphics painter = Graphics.FromImage(baseImage))
{
painter.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
DrawRects(painter); // 繪製八個控制點小矩形
}
MainPainter.DrawImage(baseImage, 0, 0);
baseImage.Dispose(); // 注意:此處銷毀傳入圖像,調用者需傳入克隆副本
}
DrawImage 到屏幕,避免閃爍。Graphics.FromImage 產生的對象需 Dispose;傳入的 Image 由調用者負責生命周期(示例中 MoveRect 內部銷毀,調用時傳 (Image)baseImage.Clone())。https://www.cnblogs.com/kevin-wu/archive/2006/12/24/601989.html
ControlPaint.DrawReversibleFrame 實現無需背景圖的 XOR 反色選區,性能更優。