我只需要用mousemove在圖片框內繪製一個矩形。 不超過圖片框的邊界。繪製各個方向的矩形
向右或向下拖動對我來說工作正常...如何使moviment反向?
我的代碼如下。
Rectangle Rect = new Rectangle();
private Point RectStartPoint;
public Pen cropPen = new Pen(Color.Red, 2);
public Form1()
{
InitializeComponent();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
RectStartPoint = e.Location;
picImagem.Invalidate();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
Point tempEndPoint = e.Location;
Rect.Location = new Point(Math.Min(RectStartPoint.X, tempEndPoint.X),
Math.Min(RectStartPoint.Y, tempEndPoint.Y));
Rect = new Rectangle(
Math.Min(tempEndPoint.X, Rect.Left),
Math.Min(tempEndPoint.Y, Rect.Top),
Math.Min(e.X - RectStartPoint.X, picImagem.ClientRectangle.Width - RectStartPoint.X),
Math.Min(e.Y - RectStartPoint.Y, picImagem.ClientRectangle.Height - RectStartPoint.Y));
picImagem.Refresh();
picImagem.CreateGraphics().DrawRectangle(cropPen, Rect);
}
}
您的確切問題,如下面所回答的,與指定問題完全相同。你的代碼中還有其他錯誤,例如未能捕獲鼠標並使用'CreateGraphics()'來繪製到控件中,而不是處理'Paint'事件或繪製到位圖中。重複的錯誤確實顯示了繪製的正確方法。如果您對其他錯誤有疑問,請提出專門針對這些問題的新問題。 –
另請參閱[此處]的答案(https://stackoverflow.com/a/2529623/3538012)和[此處](https://stackoverflow.com/a/6087367/3538012)以獲取更多靈感。 –