星期五, 1月 01, 2021

[C#] 繪製文字 - 平滑化

根據 How to: Use Antialiasing with Text 的練習筆記,反鋸齒 (平滑化) 是透過指定 TextRenderingHint 屬性,來提高文字外觀品質和可讀性

TextRenderingHint 有六種列舉,想要達到文字平滑化,基本上要指定 AntiAlias、AntiAliasGridFit、ClearTypeGridFit 這三種其中一種,ClearTypeGridFit 文字品質最佳,但效能最差,從 Understand font aliasing issues in C# 文章中可以理解到,不同字型可能會有不同測試結果,且小字型比較能看出差異

以下是使用微軟正黑體來觀察字型大小 6 和 16 文字平滑化差異
using System;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms;

namespace GraphicsSample
{
    public partial class FrmTextAntialiAsingcs : Form
    {
        public FrmTextAntialiAsingcs()
        {
            InitializeComponent();
        }

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

            FontFamily fontFamily = new FontFamily("微軟正黑體");
            SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255));

            // 字型大小 6
            Font smallFont = new Font(fontFamily, 6, FontStyle.Regular, GraphicsUnit.Pixel);
            e.Graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
            e.Graphics.DrawString(nameof(TextRenderingHint.SingleBitPerPixel), smallFont, solidBrush, new PointF(10, 10));

            e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
            e.Graphics.DrawString(nameof(TextRenderingHint.AntiAlias), smallFont, solidBrush, new PointF(10, 60));

            e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
            e.Graphics.DrawString(nameof(TextRenderingHint.ClearTypeGridFit), smallFont, solidBrush, new PointF(10, 110));

            // 字型大小 16
            Font bigFont = new Font(fontFamily, 16, FontStyle.Regular, GraphicsUnit.Pixel);
            e.Graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
            e.Graphics.DrawString(nameof(TextRenderingHint.SingleBitPerPixel), bigFont, solidBrush, new PointF(100, 10));

            e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
            e.Graphics.DrawString(nameof(TextRenderingHint.AntiAlias), bigFont, solidBrush, new PointF(100, 60));

            e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
            e.Graphics.DrawString(nameof(TextRenderingHint.ClearTypeGridFit), bigFont, solidBrush, new PointF(100, 110));

        }
    }
}
程式執行後用放大鏡來觀察會比較有感

沒有留言:

張貼留言