星期五, 6月 05, 2015

[C#] 繪圖 - 九宮格

看到有人詢問畫二維矩陣問題,想說畫個九宮格來練習繪圖相關的基礎語法
namespace WindowsFormsApplication1
{
    public partial class frmGraphics : Form
    {
        public frmGraphics()
        {
            InitializeComponent();
        }

        private void frmGraphics_Paint(object sender, PaintEventArgs e)
        {
            DataTable dt = new DataTable("Demo");
            dt.Columns.Add("Col1", typeof(int));
            dt.Columns.Add("Col2", typeof(int));
            dt.Columns.Add("Col3", typeof(int));
            dt.Rows.Add(1, 2, 3);
            dt.Rows.Add(4, 5, 6);
            dt.Rows.Add(7, 8, 9);

            int 
                MarginX = 10 ,
                MarginY = 10 ,
                RecX = 0 , 
                RecY = 0 , 
                RecWidth = 100 , 
                RecHeigh = 100 ;

            // 字在 Rec 中心
            int
                StrMarginX = RecWidth / 2,
                StrMarginY = RecHeigh / 2,
                StrX = RecWidth / 2 ,
                StrY = RecHeigh / 2;

            string data = string.Empty;

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                RecX = MarginX + (RecWidth * i);
                StrX = StrMarginX + (RecWidth * i);

                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    RecY = MarginY + (RecHeigh * j);
                    StrY = StrMarginY + (RecHeigh * j);
                    data = dt.Rows[j][i].ToString();

                    // 畫方格
                    Rectangle Rec = new Rectangle(RecX, RecY, RecWidth, RecHeigh);
                    Pen p = new Pen(Color.Black, 2);
                    e.Graphics.DrawRectangle(p, Rec);
     
                    // 填字
                    Font F = new Font("新細明體", 20, FontStyle.Bold);
                    e.Graphics.DrawString(data, F, Brushes.Blue, new PointF(StrX, StrY));
                }
            }
        }
    }
}
繪圖要畫的好,還真的有難度,發現很多問題,Orz

沒有留言:

張貼留言