實(shí)例288 GDI+繪制直線、矩形和多邊形
實(shí)例說明
在.NET中,圖形的繪制一般都是通過GDI+技術(shù)來實(shí)現(xiàn)的,簡(jiǎn)單的圖形繪制在項(xiàng)目開發(fā)中是必不可少的。本實(shí)例通過繪制直線、矩形和多邊形等簡(jiǎn)單圖形讓讀者初步了解繪圖技術(shù),實(shí)例運(yùn)行結(jié)果如圖13.1所示。
|
圖13.1 GDI+繪制直線、矩形和多邊形 |
技術(shù)要點(diǎn)
在利用GDI+繪圖時(shí),最重要的是調(diào)用類庫(kù)中的Graphics類,利用該類可以完成繪圖操作,本實(shí)例中用到了Graphics類對(duì)象的DrawLine方法、DrawRectangle方法和DrawPolygon方法,它們分別用于在畫布中繪制直線、矩形和多邊形。 下面分別介紹這幾種方法。
(1)DrawLine方法
語(yǔ)法:
public void DrawLine(Pen pen,Point pt1,Point pt2)
|
參數(shù)說明: pen:確定線條的顏色、寬度和樣式。 pt1:表示要連接的第一個(gè)點(diǎn)。 pt2:表示要連接的第二個(gè)點(diǎn)。
(2)DrawRectangle方法
語(yǔ)法:
public void DrawRectangle(Pen pen,int x,int y,int width,int height) |
參數(shù)說明: pen:確定矩形的顏色、寬度和樣式。 x:要繪制矩形的左上角的x坐標(biāo)。 y:要繪制矩形的左上角的y坐標(biāo)。 width:要繪制矩形的寬度。 height:要繪制矩形的高度。
(3)DrawPolygon方法
語(yǔ)法:
public void DrawPolygon(Pen pen,Point[] points)
|
參數(shù)說明: pen:確定多邊形的顏色、寬度和樣式。 points:表示多邊形的頂點(diǎn)。
注意:數(shù)組中的每對(duì)相鄰的兩個(gè)點(diǎn)指定多邊形的一條邊。另外,實(shí)現(xiàn)本實(shí)例前應(yīng)先引用命名空間using System.Drawing。 實(shí)現(xiàn)過程
(1)新建一個(gè)網(wǎng)站,將其命名為Ex13_01,默認(rèn)主頁(yè)為Default.aspx。
(2)主要程序代碼如下。
private void GraphicsImage( ) { int width = 440, hight = 200; Bitmap image = new Bitmap(width, hight); Graphics g = Graphics.FromImage(image); //創(chuàng)建畫布 try { g.Clear(Color.YellowGreen); //清空背景色 Font font1 = new Font("宋體", 12); //設(shè)置字體類型和大小 Brush brush = new SolidBrush(Color.Red); //設(shè)置畫刷顏色 Pen pen = new Pen(Color.Blue,1); //創(chuàng)建畫筆對(duì)象 g.DrawString("GDI+繪制直線、矩形和多邊形", font1, brush, 100, 20); g.DrawLine(pen, 40, 80, 100, 80); //繪制直線 g.DrawRectangle(pen, 130, 60, 100, 40); //繪制矩形 Point[] points = new Point[6]; points[0].X=300;points[0].Y=60; points[1].X=250;points[1].Y=80; points[2].X=300;points[2].Y=100; points[3].X=350;points[3].Y=100; points[4].X=400;points[4].Y=80; points[5].X=350;points[5].Y=60; g.DrawPolygon(pen, points); //繪制多邊形 System.IO.MemoryStream ms = new System.IO.MemoryStream( ); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); Response.ClearContent( ); Response.ContentType = "image/Gif"; Response.BinaryWrite(ms.ToArray( )); } catch(Exception ms) { Response.Write(ms.Message); } }
|
舉一反三
根據(jù)本實(shí)例,讀者可以: 繪制虛線; 繪制正方形; 繪制不規(guī)則多邊形。
|