處理圖形包括兩個步驟:
創建Graphics
對象。
使用Graphics
對象繪製線條和形狀、呈現文本或顯示與操作圖像。
Graphics
類
封裝一個GDI+繪圖圖面。提供將圖形顯示到設備的方法,此類不能被繼承。
實例化Graphics
類的幾種方法
Paint
事件的PaintEventArgs中Graphics
對象的引用
private void Form1_Paint(object sender,
System.Windows.Forms.PaintEventArgs pe)
{
// Declares the Graphics object and sets it to the Graphics object
// supplied in the PaintEventArgs.
Graphics g = pe.Graphics;
// Insert code to paint the form here.
}
- 用
CreateGraphics
方法創建Graphics
對象
Graphics g;
// Sets g to a graphics object representing the drawing surface of the
// control or form g is a member of.
g = this.CreateGraphics();
- 從
Image
創建Graphics
對象
Bitmap myBitmap = new Bitmap(@"C:\Documents and
Settings\Joe\Pics\myPic.bmp");
Graphics g = Graphics.FromImage(myBitmap);
繪製和操作形狀與圖像
Graphics
對象在創建後,可用於繪製線條和形狀、呈現文本或顯示與操作圖像。 與 Graphics
對象一起使用的主要對象有:
Pen
類 – 用於繪製線條、勾勒形狀輪廓或呈現其他幾何表示形式。Brush
類 – 用於填充圖形區域,如實心形狀、圖像或文本。Font
類 – 提供有關在呈現文本時要使用什麼形狀的說明。Color
結構 – 表示要顯示的不同顏色。
GDI+
消除鋸齒
graphics = this.CreateGraphics();
//指定抗鋸齒的呈現。
graphics.SmoothingMode = SmoothingMode.HighQuality;
SmoothingMode
枚舉
AntiAlias
指定抗鋸齒的呈現。Default
指定不抗鋸齒。HighQuality
指定抗鋸齒的呈現。HighSpeed
指定不抗鋸齒。None
指定不抗鋸齒。
Default
、None
和HighSpeed
等效,用於指定沒有應用平滑處理時的呈現方式。
AntiAlias
和HighQuality
等效,用於指定應用平滑處理時的呈現方式。
直線
繪製一條連接兩個Point
結構的線。
命名空間: System.Drawing
程序集:System.Drawing
(在 System.Drawing.dll
中)
public void DrawLine(
Pen pen,
Point pt1,
Point pt2
)
pen
類型: System.Drawing.Pen
Pen
,它確定線條的顏色、寬度和樣式。
pt1
類型: System.Drawing.Point
Point
結構,它表示要連接的第一個點。
pt2
類型: System.Drawing.Point
Point 結構,它表示要連接的第二個點。
示例:
// Create pen.
Pen blackPen = new Pen(Color.Black, 3);
// Create points that define line.
Point point1 = new Point(100, 100);
Point point2 = new Point(500, 100);
// Draw line to screen.
e.Graphics.DrawLine(blackPen, point1, point2);
測量字符串的高度
參數
text
類型: System.String
要測量的字符串。
font
類型: System.Drawing.Font
Font,它定義字符串的文本格式。
string temp = "ABCD";
Font font = new Font("宋體", 9);
Graphics g = this.CreateGraphics();
SizeF sizeF = g.MeasureString(temp, font);
MessageBox.Show(sizeF.Width + " " + sizeF.Height);
g.Dispose();