Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9707

C# 文字の色を部分的に変えて描画する

$
0
0
やりたいこと カラオケの字幕のような感じで描画する。 画面キャプチャ ソースコード using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using System.Windows.Forms; class DrawStrSample : Form { static readonly int W = 400; static readonly int H = 200; PictureBox pct; DrawStrSample() { ClientSize = new Size(W,H); Controls.Add(pct = new PictureBox(){ Size = new Size(W,H), Image = new Bitmap(W,H), }); Load += (s,e)=>{Draw("てすと");}; } void Draw(string text) { var g = Graphics.FromImage(pct.Image); var rectDraw = new Rectangle(0, 0, W, H); int leftPartWitdh = (int)(rectDraw.Width * 0.45); // 左側用と右側用の、色と描画領域 Brush[] brush = { new SolidBrush(Color.Blue) , new SolidBrush(Color.Gray) }; Pen[] pen = { new Pen(Color.Blue,3.0f), new Pen(Color.Gray,3.0f) }; // 表示確認用 Rectangle[] rectClip = { new Rectangle(rectDraw.X, rectDraw.Y, leftPartWitdh, rectDraw.Height), new Rectangle(rectDraw.X + leftPartWitdh, rectDraw.Y, rectDraw.Width - leftPartWitdh, rectDraw.Height) }; // g.FillRectangle(Brushes.Gray, rectDraw); // DrawStringにアンチエイリアスを適用する // g.TextRenderingHint = TextRenderingHint.AntiAlias; // アンチエイリアスを適用する g.SmoothingMode = SmoothingMode.HighQuality; var gp = new GraphicsPath(); var ff = new FontFamily("MS ゴシック"); var sf = new StringFormat(); sf.Alignment = StringAlignment.Center; // String, FontFamily, fontStyle, emSize, layoutRect, StringFormat gp.AddString(text, ff, 0, 100, rectDraw, sf); // 左右をクリップを切り替えながら、2度描画する for ( int i=0; i<2; i++ ) { g.SetClip(rectClip[i]); //g.DrawString(text, font, brush[i], rectDraw , sf); //文字列の中を塗りつぶす g.FillPath(brush[i], gp); g.DrawRectangle(pen[i], rectClip[i]); // 確認用 } // clipを元に戻す g.SetClip(rectDraw); //文字列の縁を描画する g.DrawPath(Pens.Black, gp); g.Dispose(); } [STAThread] static void Main(string[] args) { Application.Run(new DrawStrSample()); } } 参考サイト 「C#の画像作成で文字を部分的に色を変えたい」(1) Insider.NET - @IT .NET GraphicsPath.AddStringで縁取り文字を描きたい - Qiita 文字列を縁取りをして描画する - .NET Tips (VB.NET,C#...) アンチエイリアス処理をして描画する - .NET Tips (VB.NET,C#...) Graphics.SetClip Method (System.Drawing) | Microsoft Docs GraphicsPath.AddString Method (System.Drawing.Drawing2D) | Microsoft Docs

Viewing all articles
Browse latest Browse all 9707

Trending Articles