認(rèn)知尚淺,如有錯(cuò)誤,愿聞其詳!
概述
?? 初識Graphics繪圖時(shí)走了很多彎路,很多時(shí)候根據(jù)網(wǎng)上的教程完成了繪制,卻因項(xiàng)目的需求上遇上了各種問題,導(dǎo)致達(dá)不到自己需要的效果。而且對于Graphics的繪制過程及機(jī)制上不了解,很大程度遇到問題就懵逼了!
??其實(shí)利用Graphics繪制一個(gè)圖形很簡單,容易出現(xiàn)問題的是在于你畫了之后他什么時(shí)候被銷毀了,什么時(shí)候該重繪。這兩個(gè)處理不好,就是突然消失了,或者是浪費(fèi)資源。
我遇到的問題
??在我的工作中,我需要在Panel中使用Graphics繪制幾條線,來形成一個(gè)矩形簡單表格,將內(nèi)容包括起來,便于查看。可是在窗口初始加載后顯示正常,但在切換窗口后卻消失了。效果如下:

繪制.png
實(shí)現(xiàn)
實(shí)現(xiàn)上很簡單,一般繪制都是在重寫OnPaint中去實(shí)現(xiàn)繪制。代碼如下:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
//畫方框
int width_P = panel_Left.Size.Width;//寬
int height_P = panel_Left.Size.Height;//高
int topSpace = 100;//線上邊距
int botSpace = 40;//線上邊距
int leftSpace = 9;//線左右邊距
int rowSpace = 30;//行距
Pen pen = new Pen(Color.Black, 2f);
Pen pen_1 = new Pen(Color.Black, 1.5f);//創(chuàng)建畫筆
using (Graphics g = panel_Left.CreateGraphics())//使用using括起來,繪制完成立即銷毀
{
//開始繪制圖形
g.DrawLine(pen, new Point(leftSpace, topSpace), new Point(width_P - leftSpace, topSpace));//上下
g.DrawLine(pen, new Point(leftSpace, height_P - botSpace), new Point(width_P - leftSpace, height_P - botSpace));
g.DrawLine(pen_1, new Point(leftSpace, topSpace + rowSpace), new Point(width_P - (leftSpace + 1), topSpace + rowSpace));//上下
g.DrawLine(pen_1, new Point(leftSpace, height_P - (botSpace + rowSpace)), new Point(width_P - (leftSpace + 1), height_P - (botSpace + rowSpace)));
g.DrawLine(pen_1, new Point(leftSpace, height_P - (botSpace + rowSpace * 2)), new Point(width_P - (leftSpace + 1), height_P - (botSpace + rowSpace * 2)));
g.DrawLine(pen, new Point(leftSpace + 1, topSpace), new Point(leftSpace + 1, height_P - botSpace));//左右
g.DrawLine(pen, new Point(width_P - (leftSpace + 1), topSpace), new Point(width_P - (leftSpace + 1), height_P - botSpace));
}
}
但是,意想不到的是在窗口初始化后能正常顯示,而在切換窗口時(shí),繪制的橫線卻消失了。
當(dāng)時(shí)也大概了解起因是應(yīng)為窗體在切換后被重繪了,圖像被覆蓋住了,導(dǎo)致看不見了。
后來,我也嘗試的去單步調(diào)試,在窗口獲得焦點(diǎn)后,重繪時(shí),OnPaint并沒有被執(zhí)行,所以得到以下方法:
private void Frm_SettlementMsg_Activated(object sender, EventArgs e)
{
//將整個(gè)窗口設(shè)置為無效,致觸發(fā)重繪
this.Invalidate();
}
強(qiáng)制性的在窗口處于激活狀態(tài)時(shí)執(zhí)行刷新窗口,觸發(fā)重繪,進(jìn)而觸發(fā)重新繪制圖形。