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));
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM