using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; namespace BsWidget { internal static class GdiPlusExt { public static void ClearRect(this Graphics g, Color color, float x, float y, float w, float h) { g.SetClip(new RectangleF(x, y, w, h)); g.Clear(color); g.ResetClip(); } public static void SetHighQuality(this Graphics g) { g.CompositingMode = CompositingMode.SourceOver; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; } public static SizeF DrawStringWithOutline(this Graphics g, string text, Font font, float x, float y, Color outlineColor, Color fillColor, float outlineWidth = 1) { // assuming g is the Graphics object on which you want to draw the text using var p = new GraphicsPath(); p.AddString( text, // text to draw font.FontFamily, // or any other font family (int)FontStyle.Regular, // font style (bold, italic, etc.) g.DpiY * font.Size / 72, // em size new PointF(x, y), // location where to draw text new StringFormat()); // set options here (e.g. center alignment) using var outlinePen = new Pen(outlineColor, outlineWidth); using var fillBrush = new SolidBrush(fillColor); g.FillPath(fillBrush, p); g.DrawPath(outlinePen, p); return p.GetBounds().Size; } public static void DrawRoundedRectangle(this Graphics graphics, Pen pen, RectangleF bounds, int cornerRadius) { if (graphics == null) throw new ArgumentNullException("graphics"); if (pen == null) throw new ArgumentNullException("pen"); using var path = RoundedRect(bounds, cornerRadius); graphics.DrawPath(pen, path); } public static void FillRoundedRectangle(this Graphics graphics, Brush brush, RectangleF bounds, float cornerRadius) { if (graphics == null) throw new ArgumentNullException("graphics"); if (brush == null) throw new ArgumentNullException("brush"); using var path = RoundedRect(bounds, cornerRadius); graphics.FillPath(brush, path); } public static SizeF DrawStringWithRoundedRect(this Graphics g, string text, Font font, float x, float y, Brush textbBrushe, Brush bgBrush, float radus = 10) { var sz = g.MeasureString(text, font); g.FillRoundedRectangle(bgBrush, new RectangleF(x, y, sz.Width, sz.Height), radus); g.DrawString(text, font, textbBrushe, x, y); return sz; } private static GraphicsPath RoundedRect(RectangleF bounds, float radius) { var diameter = radius * 2; var size = new SizeF(diameter, diameter); var arc = new RectangleF(bounds.Location, size); var path = new GraphicsPath(); if (Math.Abs(radius) < 0.00001) { path.AddRectangle(bounds); return path; } // top left arc path.AddArc(arc, 180, 90); // top right arc arc.X = bounds.Right - diameter; path.AddArc(arc, 270, 90); // bottom right arc arc.Y = bounds.Bottom - diameter; path.AddArc(arc, 0, 90); // bottom left arc arc.X = bounds.Left; path.AddArc(arc, 90, 90); path.CloseFigure(); return path; } } }