標籤:send private bsp 視窗 中間 res 圖片 static invalid
視窗重新整理的時候,會產生Paint事件,那麼我們給這個事件添加一個處理函數。然後在這個函數裡畫圖。就能保證所畫的圖不被重新整理掉,
它可以總是顯示。Paint事件對應的委託是:public delegate void PaintEventHandler(object sender, PaintEventArgs e);
樣本1:在視窗中間畫一根線。(建立WindowsForms應用程式)
Graphics g = this.CreateGraphics(); Pen p = new Pen(Color.Black); //在螢幕中間畫一根線 g.DrawLine(p, 0, this.Height / 2, this.Width, this.Height / 2); //畫一個矩形 g.DrawRectangle(p, 50, 50, 200, 100); //畫一個圓 g.DrawEllipse(p, 150, 150, 100, 100); //手動釋放資源 g.Dispose(); p.Dispose();
樣本2:一個填充矩形
private void formPaint(Object sender, PaintEventArgs e) { Graphics graphics = e.Graphics; //藍色畫刷 SolidBrush brush = new SolidBrush(Color.FromArgb(0, 0, 255)); //一個矩形 Rectangle rect = new Rectangle(0, 0, 100, 100); //填充一個矩形 graphics.FillRectangle(brush, rect); }
樣本3:畫一張png圖片(用PNG是因為可以顯示透明的圖片,GIF圖片也有這個作用)
private void formPaint(Object sender, PaintEventArgs e) { Graphics graphics = e.Graphics; //載入圖片 Image img = Image.FromFile(Application.StartupPath+ @"\111.png"); //圖片顯示起始位置 Point strPoint=new Point(50,50); //不限制大小繪製 graphics.DrawImage(img, strPoint); //縮小圖片繪製,限制在一個矩形內 Rectangle rect=new Rectangle(50,50,100,100); graphics.DrawImage(img, rect); }
樣本4:用DrawString顯示文字
DrawString在Grahpics類裡有好幾個重載,有的可以讓字串在一個矩形內顯示,有的可以使用特定的顯示格式。這裡就不做詳細介紹了。
只講比較常用的。
看例子吧,處理鍵盤輸入字元事件,在視窗顯示輸入的字元。如下:
public partial class Form1 : Form { public static String strText = ""; public Form1() { InitializeComponent(); this.Paint += formPaint; this.KeyPress += formKeyPress; } private void formPaint(Object sender, PaintEventArgs e) { Graphics graphics = e.Graphics; //建立畫刷 SolidBrush brush=new SolidBrush(Color.FromArgb(0,255,0)); //建立字型 Font font=new Font("宋體",20f); //顯示字串,在一個矩形內 graphics.DrawString(strText, font, brush, this.ClientRectangle); } private void formKeyPress(object sender, KeyPressEventArgs e) { strText += e.KeyChar; //重新整理整個視窗 this.Invalidate(); } }
C# GDI+編程(一)