標籤:style blog http io color ar os sp for
原文:C# Graphic 繪製圓、三角形、橢圓、圖片
在form和panel上可以繪製圖形,線段,圓,文字,圖形等等。
繪製代碼必須放在OnPaint()函數裡面,因為表單重新整理的時候,都會調用該函數,重新重新整理所繪的圖。
範例程式碼在Panel上繪製圖形來簡單的描述下繪線和繪圖原理。
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;using System.Reflection;namespace TestGraphic{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void panel1_Paint(object sender, PaintEventArgs e) { Graphics gc = e.Graphics; /// 設定繪圖的顏色 Brush greenBrush = new SolidBrush(Color.Green); int radius = 30; // 繪製圓,(0, 0)為左上方的座標,radius為直徑 gc.FillEllipse(greenBrush, 0, 0, radius, radius); Brush yellowBush = new SolidBrush(Color.Yellow); // 繪製橢圓,其實圓時橢圓的特殊的一種,即兩個定點重合, (50, 60)為左上方的座標, // 70位橢圓的寬度,100位橢圓的高度 gc.FillEllipse(yellowBush, 50, 60, 70, 100); // 繪製三角形,指定紅色和線寬5。三個頂點為(150,160) (200, 210) (280, 180),繪製三條連線。 Pen pen = new Pen(Color.Red, 5); gc.DrawLine(pen, 150, 160, 200, 210); gc.DrawLine(pen, 200, 210, 280, 180); gc.DrawLine(pen, 150, 160, 280, 180); /// 繪製矩形,(50,300)左上方座標,110位寬度, 80為高度。 gc.DrawRectangle(pen, 50, 300, 110, 80); Brush blueBrush = new SolidBrush(Color.Blue); /// 繪製文本 gc.DrawString("Graphic繪製圖形的例子", new Font("宋體", 20, FontStyle.Italic), blueBrush, new PointF(300, 400)); /// 繪製圖片 TestGraphic.Properties.Resources.niang為圖片在資源中的名稱,可以先將圖片設定為Panel的背景圖, /// 獲得圖片的名稱,然後將Panel的背景圖清空。(400,20)是圖片左上方座標,300,300是圖片將要顯示的寬度和高度, /// 並不是圖片本身的寬度和高度。 Image image = global::TestGraphic.Properties.Resources.niang; gc.DrawImage(image, new Rectangle(400, 20, 300, 300)); } }}
C# Graphic 繪製圓、三角形、橢圓、圖片