※ 引述《LLL333 (數學很重要)》之銘言:
: 我想畫個能拖曳的矩形, 可是以下的程式碼跑出來是
: 拖曳的時候會有矩形出現, 但是滑鼠停住時(此時左鍵還按著),
: 矩形就消失了, 請問要怎麼做才能讓矩形的形狀一直出現
: private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
: {
: if ((e.Button == MouseButtons.Left) && enable)
: {
: Graphics g = this.pictureBox1.CreateGraphics();
: Pen p = new Pen(Color.Red);
: //計算矩形位置
: tempX = e.X;
: tempY = e.Y;
: tempX = Clamp(tempX, 0, 319);
: tempY = Clamp(tempY, 0, 239);
: width = Math.Abs(tempX - OldX);
: height = Math.Abs(tempY - OldY);
: if (tempX > OldX)
: tempX = OldX;
: if (tempY > OldY)
: tempY = OldY;
: g.DrawRectangle(p, tempX , tempY , width, height);
: this.pictureBox1.Invalidate();
: }
: }
其實有很多方法,實作的方法都大同小異
這裡我選擇繼承一個PictureBox
以下Source code是我憑印象寫的,很抱歉目前手上沒Visual Studio
也許語法上有錯,請各位前輩見諒
然各位前輩有更好的作法,也請指教
謝謝!
public class pb : PictureBox
{
Rectangle block;
bool isMouseDown;
Point ptBegin, ptEnd;
override OnPaint(object sender, PaintEventArgs pe)
{
if (block != null)
pe.Graphics.DrawRectangle(Pens.White, block);
}
//參數我就省略不打了,請原諒我的懶:P
override OnMouseDown(......)
{
isMouseDown = true;
ptBeg = new Point(e.X, e.Y);
}
override OnMouseMove(....)
{
if (isMouseDown)
{
ptEnd = new Point(e.X, e.Y);
Block = getRect(ptBeg, ptEnd);
invalidate();
}
}
override OnMouseUp(.....)
{
isMouseDown = false;
}
Rectangle getRect(Point begin, Point end)
{
//這裡實作取得2個point間的rectangle
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.137.134.49