作者feobzq (0.0)
看板C_Sharp
標題Re: [問題] 小畫家功能
時間Sun Jul 21 15:10:13 2019
※ 引述《amen1387 (MyBad)》之銘言:
: ※ 引述《fantoccini (失控的顏色)》之銘言:
: : 這幾天為了寫視窗開始學C#
: : 再練習的時候遇到一個問題
: : 例如我要畫一個矩形
: : 當Mouse按下後 然後移動 然後放開
: : 最後的結果是一個矩形 但是
: : 我的滑鼠在移動的過程中 無法看出
: : 這個矩形跟隨著你的滑鼠移動
: : 簡單的說 就是小畫家 圈選矩形的那個功能
: : 感覺上是要一直重繪 不知道是不是這樣
: 我把drawline寫在mouse_up的話,就跟原本樓主的問題一樣,但試著寫在mouse_move他就
: 會一直出現
: 我現在有想到的方式是在mousedown的時候把picture box擷取起來
: Bitmap lastimage=new Bitmap(picturebox1.width,picturebox1.height);
: Garphcs Imagegrapics=Graphics.FromImage(lastimage);
: 然後在mousemove時
: Graphics p =pictureBox1.CreateGraphics();
: if(e.Button==MouseButton.Left)
: {
: p=image graphics;
: p.DrawLine(pen1,downX,downY,e.X,e.Y);
: }
: 可是這樣寫連畫出來都沒有,不知道哪裡出了問題
: 。
我用兩張Bitmap在MouseMove和MouseUp交互替換PictureBox.Image
MouseMove時先用MouseDown時先存過的Bitmap做刷新
Graphics G;
Point P;
Bitmap Bmp1, Bmp2;
bool mouseDown = false;
private void Form1_Load(object sender, EventArgs e)
{
Bmp1 = new Bitmap(pictureBox1.Width,pictureBox1.Height);
pictureBox1.Image = Bmp1;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
P = e.Location;
mouseDown = true;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
Bmp2 = (Bitmap)Bmp1.Clone();
G = Graphics.FromImage(Bmp2);
pictureBox1.Image = Bmp2;
Draw(e);
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
pictureBox1.Image = Bmp1;
G = Graphics.FromImage(Bmp1);
Draw(e);
}
void Draw(MouseEventArgs e)
{
Point P1 = P;
Point P2 = e.Location;
float width = P2.X - P1.X;
float height = P2.Y - P1.Y;
int tmp;
if (width < 0)
{
tmp = P2.X;
P2.X = P1.X;
P1.X = tmp;
width = -width;
}
if (height < 0)
{
tmp = P2.Y;
P2.Y = P1.Y;
P1.Y = tmp;
height = -height;
}
G.DrawRectangle(new Pen(Brushes.Black), P1.X, P1.Y, width,
height);
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.143.9.68 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1563693019.A.938.html
推 ideaup: move時只畫在bmp2 上且顯示它,好像可以,很簡單 07/21 18:54
→ ideaup: 每次move都要做,bmp1.clone()+bmp2.dispose(),費時 07/21 19:27
推 anumis: 宣告2張 bmp,一張拿來顯示,一張拿來繪圖,進到 paint 時 07/22 10:56
→ anumis: ,先把圖2清空後再做繪圖程式碼,等東西都完完後,圖1再清 07/22 10:56
→ anumis: 空把圖2畫上去 07/22 10:56
→ anumis: 你要有個概念,一但進了 picturebox 之類的"螢幕顯示型元 07/22 10:56
→ anumis: 件",那就要跟實際硬體做io,速度就不比你在記憶體內處理 07/22 10:56
→ anumis: 了,所以才需要分成"表層/理層"的方式去做,市面上所有遊 07/22 10:56
→ anumis: 戲引擎都是這麼幹的。 07/22 10:57
→ anumis: 然後沒必要做 dispose,直接同一個記憶體區域重複利用就好 07/22 10:59
→ anumis: ,可可省掉一直重複宣告記/釋放憶體空間的時間 07/22 10:59
→ feobzq: 兩位大大說的都看得懂,只是要怎麼修比較好?(若不用WinAPI 07/22 22:20
→ anumis: 我講的是方法,實做就用內建的 Graphic + bitmap 做就好了 07/27 14:33