在图片框上画一个矩形
本文关键字:一个 | 更新日期: 2023-09-27 18:22:17
当这个窗体打开时,它有一个全屏的背景图像,用户可以用鼠标向下拖动并绘制一个矩形,稍后将用于裁剪背景图像。我遇到的问题是,当表单绘制时,它没有绘制矩形,所以用户不知道他们选择的区域
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Quick_Screenshot
{
public partial class Crop : Form
{
private Rectangle croprect = Rectangle.Empty;
private bool mouseDown = false;
private bool selectedArea = false;
Point sp, ep;
Bitmap background;
public Rectangle CropArea
{
get { return croprect; }
}
public bool SelectedArea
{
get { return selectedArea; }
}
public Crop(Bitmap image)
{
InitializeComponent();
background = image;
picBox.MouseDown += new MouseEventHandler(Crop_MouseDown);
picBox.MouseUp += new MouseEventHandler(Crop_MouseUp);
picBox.MouseMove += new MouseEventHandler(Crop_MouseMove);
picBox.Paint += new PaintEventHandler(Crop_Paint);
}
private void Crop_Load(object sender, EventArgs e)
{
picBox.Image = (Image)background;
}
private void Crop_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
this.Close();
else
{
mouseDown = true;
sp = ep = e.Location;
}
}
private void Crop_MouseUp(object sender, MouseEventArgs e)
{
ep = e.Location;
mouseDown = false;
croprect = GetRectangle(sp, ep);
if (croprect.Width > 10 && croprect.Height > 10)
{
selectedArea = true;
}
else
{
croprect = Rectangle.Empty;
Taskbar.Balloon("Selected area too small", "Quick Screenshot", ToolTipIcon.Error);
}
this.Close();
}
private void Crop_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
ep = e.Location;
Update();
}
}
private void Crop_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(Pens.Red, GetRectangle(sp, ep));
e.Graphics.Save();
}
private Rectangle GetRectangle(Point p1, Point p2)
{
return new Rectangle(
Math.Min(p1.X, p2.X),
Math.Min(p1.Y, p2.Y),
Math.Abs(p1.X - p2.X),
Math.Abs(p1.Y - p2.Y)
);
}
}
}
您应该在picBox变量上调用Invalidate()方法来刷新控件。
取而代之的是:
private void Crop_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
ep = e.Location;
Update();
}
}
使用此:
private void Crop_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
ep = e.Location;
picBox.Invalidate();
}
}
您应该调用Invalidate()
而不是Update()