星期六, 12月 26, 2020

[C#] 繪製文字 - 對齊

根據 作法:對齊繪製的文字 的練習筆記
using System;
using System.Drawing;
using System.Windows.Forms;

namespace GraphicsSample
{
    public partial class FrmText : Form
    {

        public FrmText()
        {
            InitializeComponent();
        }

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

            DrawStringAlignment(e);
            RenderTextCenter(e);
        }

        Font fontAlignment = new Font("微軟正黑體", 12, FontStyle.Bold);
        Pen penRect = Pens.Black;

        private void DrawStringAlignment(PaintEventArgs e)
        {
            string text = "Use StringFormat and Rectangle objects to center text in a rectangle.";
            Rectangle rect = new Rectangle(10, 10, 130, 140);

            // Alignment:水平對齊
            // LineAlignment:垂直對齊
            StringFormat stringFormat = new StringFormat();
            stringFormat.Alignment = StringAlignment.Center;
            stringFormat.LineAlignment = StringAlignment.Center;

            // 在矩形內繪製文字
            e.Graphics.DrawString(text, fontAlignment, Brushes.Blue, rect, stringFormat);
            e.Graphics.DrawRectangle(penRect, rect);
        }

        private void RenderTextCenter(PaintEventArgs e)
        {
            string text = "Use TextFormatFlags and Rectangle objects to center text in a rectangle.";
            Rectangle rect = new Rectangle(150, 10, 130, 140);

            // HorizontalCenter:水平置中
            // VerticalCenter:垂直置中
            // WordBreak:在字的結尾讓文字分行
            TextFormatFlags flags = TextFormatFlags.HorizontalCenter |
                TextFormatFlags.VerticalCenter |
                TextFormatFlags.WordBreak;

            // 在矩形內繪製文字
            TextRenderer.DrawText(e.Graphics, text, fontAlignment, rect, Color.Blue, flags);
            e.Graphics.DrawRectangle(penRect, rect);
        } 
    }
}

沒有留言:

張貼留言