C# GDI基礎

處理圖形包括兩個步驟:
創建Graphics對象。
使用Graphics對象繪製線條和形狀、呈現文本或顯示與操作圖像。

Graphics

封裝一個GDI+繪圖圖面。提供將圖形顯示到設備的方法,此類不能被繼承。

實例化Graphics類的幾種方法

  1. 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.
}
  1. 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();
  1. 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 指定不抗鋸齒。

DefaultNoneHighSpeed等效,用於指定沒有應用平滑處理時的呈現方式。

AntiAliasHighQuality等效,用於指定應用平滑處理時的呈現方式。

直線

繪製一條連接兩個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);

測量字符串的高度

使用Graphics.MeasureString方法

參數
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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章