我正在尝试使用我的鼠标制作一个可重复调整大小的方框,但是如果我快速拖动鼠标,则非常明显的是它偏离应该的位置,例如http://imgur.com/a/sglGv(红色应该是它的位置,黑色就是它的所在。)
using System.Drawing;
using System.Windows.Forms;
using System;
using System.Drawing.Drawing2D;
namespace WindowsFormsApp6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TransparencyKey = Color.SaddleBrown;
canvas.MouseDown += new MouseEventHandler(canvas_MouseDown);
canvas.MouseUp += new MouseEventHandler(canvas_MouseUp);
canvas.MouseMove += new MouseEventHandler(canvas_MouseMove);
Load += new EventHandler(Form1_Load);
//typeof(Panel).InvokeMember("DoubleBuffered", BindingFlags.SetProperty| BindingFlags.Instance | BindingFlags.NonPublic, null,canvas, new object[] { true });
}
private Bitmap m_OriginalImage = null;
private int X0, Y0, X1, Y1;
private bool SelectingArea = false;
private Bitmap SelectedImage = null;
private Graphics SelectedGraphics = null;
private void Form1_Load(object sender, EventArgs e)
{
m_OriginalImage = new Bitmap(canvas.Image);
KeyPreview = true;
}
private void canvas_MouseDown(object sender, MouseEventArgs e)
{
SelectingArea = true;
X0 = e.X;
Y0 = e.Y;
SelectedImage = new Bitmap(m_OriginalImage);
SelectedGraphics = Graphics.FromImage(SelectedImage);
canvas.Image = SelectedImage;
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
if (!SelectingArea) return;
X1 = e.X;
Y1 = e.Y;
SelectedGraphics.DrawImage(m_OriginalImage, 0, 0);
using (Pen select_pen = new Pen(Color.Red))
{
select_pen.DashStyle = DashStyle.Dash;
Rectangle rect = MakeRectangle(X0, Y0, X1, Y1);
//ControlPaint.DrawReversibleFrame(rect,this.BackColor, FrameStyle.Dashed);
SelectedGraphics.DrawRectangle(select_pen, rect);
}
canvas.Refresh();
}
private void canvas_MouseUp(object sender, MouseEventArgs e)
{
if (!SelectingArea) return;
SelectingArea = false;
SelectedImage = null;
SelectedGraphics = null;
canvas.Image = m_OriginalImage;
canvas.Refresh();
Rectangle rect = MakeRectangle(X0, Y0, X1, Y1);
if ((rect.Width > 0) && (rect.Height > 0))
{
MessageBox.Show(rect.ToString());
}
}
private Rectangle MakeRectangle(int x0, int y0, int x1, int y1)
{
return new Rectangle(
Math.Min(x0, x1),
Math.Min(y0, y1),
Math.Abs(x0 - x1),
Math.Abs(y0 - y1));
}
}
}
我已经尝试了从计时器到线程的所有想法。
任何保持60 fps的建议都会受到重视。