DrawStringメソッドで描画する文字列をアンチエイリアスで描画する場合はこちらの記事を参照して下さい。
C#でアンチエイリアスを有効にして線や円をキャンバスに描画するコードを紹介します。
C#ではデフォルトの状態ではGraphicsオブジェクトのDrawLineメソッドやDrawEllipseメソッドを呼び出して、線や円を描画した場合、
アンチエイリアスの無い線が描画されます。
この記事では、アンチエイリアスを有効にして、線や円を描画するコードを紹介します。
描画時にアンチエイリアスを有効にする場合は描画するGraphicsオブジェクトのSmoothingModeプロパティにSmoothingMode.AntiAlias
を設定します。
[Graphicsオブジェクト].SmoothingMode = SmoothingMode.AntiAlias;
下図のフォームを作成します。フォームにPanelコントロールを1つ配置します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AntiAliasDemo
{
public partial class FormAntiAliasDraw : Form
{
public FormAntiAliasDraw()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
Pen p1 = new Pen(Color.FromArgb(0x2f,0x95,0x10), 2);
e.Graphics.DrawLine(p1, 24, 12, 256, 96);
Pen p2 = new Pen(Color.FromArgb(0x22,0x88,0xd7), 4);
e.Graphics.DrawEllipse(p2, 220, 120, 64, 64);
}
}
}
GraphicsオブジェクトのSmoothingMode プロパティにSmoothingMode.AntiAlias
を設定します。
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
DrawLineメソッドで線を描画します。
Pen p1 = new Pen(Color.FromArgb(0x2f,0x95,0x10), 2);
e.Graphics.DrawLine(p1, 24, 12, 256, 96);
DrawEllipseメソッドで円を描画します。
Pen p2 = new Pen(Color.FromArgb(0x22,0x88,0xd7), 4);
e.Graphics.DrawEllipse(p2, 220, 120, 64, 64);
プロジェクトを実行します。下図の画面が表示されます。円や斜めの直線がアンチエイリアスされて描画できています。
比較用にデフォルトの描画結果も確認します。
下図のフォームを作成します。先のプログラムから変更はないです。
以下のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AntiAliasDemo
{
public partial class FormAntiAliasDraw : Form
{
public FormAntiAliasDraw()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Pen p1 = new Pen(Color.FromArgb(0x2f,0x95,0x10), 2);
e.Graphics.DrawLine(p1, 24, 12, 256, 96);
Pen p2 = new Pen(Color.FromArgb(0x22,0x88,0xd7), 4);
e.Graphics.DrawEllipse(p2, 220, 120, 64, 64);
}
}
}
SmoothingMode プロパティに SmoothingMode.AntiAlias
を設定する以下のコードを削除しデフォルトの状態で画面に図形を描画します。
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
プロジェクトを実行します。下図の画面が表示されます。アンチエイリアスされていない描画結果が確認できます。