文字的顯示可以使用Label處理,
但如果背景顏色與文字顏色太接近的話,
文字就會看不清楚了,
這邊提供一個文字描邊的方式,
讓文字有個明顯的邊界利於辨識。
private static void DrawString(string text, Font font, Brush brush, float x, float y, Graphics graphics) { //計算文字大小 var textSize = TextRenderer.MeasureText(text, font); //文字轉圖片 using (var tmpBitmap = new Bitmap(textSize.Width, textSize.Height)) { using (var g = Graphics.FromImage(tmpBitmap)) { //文字優化(去鋸齒) g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.NearestNeighbor; g.CompositingMode = CompositingMode.SourceOver; g.CompositingQuality = CompositingQuality.HighSpeed; g.PixelOffsetMode = PixelOffsetMode.HighSpeed; g.TextRenderingHint = TextRenderingHint.AntiAlias; using (GraphicsPath path = new GraphicsPath()) { //取得路徑 path.AddString(text, font.FontFamily, (int)FontStyle.Bold, font.Size, new Point(0, 0), new StringFormat()); using (var pen = new Pen(new SolidBrush(Color.Black), font.Size / 10)) { //描邊 g.DrawPath(pen, path); } //填字 g.FillPath(brush, path); brush.Dispose(); } } //畫圖片 graphics.DrawImage(tmpBitmap, new PointF(x, y)); } }
為了不同情況下,文字放的位置不同,多了StringAlignment可選擇。
private enum StringAlignment { Left, Right, Center }
新增StringAlignment至DrawString
private static void DrawString(string text, Font font, Brush brush, float x, float y, Graphics graphics, StringAlignment alignment) { //計算文字大小 var textSize = TextRenderer.MeasureText(text, font); //文字轉圖片 using (var tmpBitmap = new Bitmap(textSize.Width, textSize.Height)) { using (var g = Graphics.FromImage(tmpBitmap)) { //文字優化(去鋸齒) g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.NearestNeighbor; g.CompositingMode = CompositingMode.SourceOver; g.CompositingQuality = CompositingQuality.HighSpeed; g.PixelOffsetMode = PixelOffsetMode.HighSpeed; g.TextRenderingHint = TextRenderingHint.AntiAlias; using (GraphicsPath path = new GraphicsPath()) { //取得路徑 path.AddString(text, font.FontFamily, (int)FontStyle.Bold, font.Size, new Point(0, 0), new StringFormat()); using (var pen = new Pen(new SolidBrush(Color.Black), font.Size / 10)) { //描邊 g.DrawPath(pen, path); } //填字 g.FillPath(brush, path); brush.Dispose(); } } //畫圖片 switch (alignment) { case StringAlignment.Left: graphics.DrawImage(tmpBitmap, new PointF(x, y - textSize.Height / 2f)); break; case StringAlignment.Right: graphics.DrawImage(tmpBitmap, new PointF(x - textSize.Width, y - textSize.Height / 2f)); break; case StringAlignment.Center: graphics.DrawImage(tmpBitmap, new PointF(x - textSize.Width / 2f, y - textSize.Height / 2f)); break; } } }
沒有留言:
張貼留言