星期四, 12月 24, 2020

[C#] 繪製實心矩形

根據 作法:在 Windows Form 上繪製實心矩形 的筆記
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void DrawRectangle()
        {
            using (Graphics g = this.CreateGraphics())
            using (Pen p = new Pen(Color.Black))
            using (SolidBrush b = new SolidBrush(Color.LightBlue))
            {
                Rectangle rec = new Rectangle(20, 20, 300, 300);

                p.Width = 10;
                p.DashStyle = DashStyle.Solid;
                g.DrawRectangle(p, rec);

                g.FillRectangle(b, rec);
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            DrawRectangle();
        }
    }
}
 文章內注意事項
You should always call Dispose on any objects that consume system resources, such as Brush and Graphics objects. 
繪製過程假如沒有特別需求,EX:Pen 需要指定寬度 (Width)、線條樣式 (DashStyle) 等需求,.NET Framework 有提供 BrushesPens 靜態類別可以直接指定顏色

沒有留言:

張貼留言