Advertisement
Jimi2000

GDI+ Graphics Draw/Measure trimmed

Dec 5th, 2019
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.26 KB | None | 0 0
  1.     public partial class frmSOTest1036 : Form
  2.     {
  3.         public frmSOTest1036()
  4.         {
  5.             InitializeComponent();
  6.             this.ResizeRedraw = true;
  7.         }
  8.  
  9.         protected override void OnPaint(PaintEventArgs e)
  10.         {
  11.             base.OnPaint(e);
  12.  
  13.             e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
  14.             Font font = new Font("Century Gothic", 18F, FontStyle.Bold, GraphicsUnit.Point);
  15.             string demo = "[Emergency 123]";
  16.  
  17.             StringFormat fmtTrimmed = new StringFormat(StringFormat.GenericTypographic) {
  18.                 Alignment = StringAlignment.Near,
  19.                 LineAlignment = StringAlignment.Near,
  20.                 Trimming = StringTrimming.EllipsisCharacter,
  21.             };
  22.  
  23.             StringFormat fmtNotTrimmed = new StringFormat(StringFormat.GenericTypographic) {
  24.                 Alignment = StringAlignment.Center,
  25.                 LineAlignment = StringAlignment.Near,
  26.             };
  27.  
  28.             try {
  29.                 Rectangle boundsHeader = new Rectangle(10, 10, this.ClientSize.Width - 20, (int)font.GetHeight() + 8);
  30.                 SizeF textSize = e.Graphics.MeasureString(demo, font, boundsHeader.Size, fmtNotTrimmed);
  31.  
  32.                 boundsHeader.Inflate(1, 1);
  33.                 e.Graphics.DrawRectangle(Pens.Blue, boundsHeader);
  34.  
  35.                 float textCenterBounds = (boundsHeader.Width - textSize.Width) / 2;
  36.                 e.Graphics.DrawRectangle(Pens.Green, boundsHeader.X + textCenterBounds, boundsHeader.Y, textSize.Width, textSize.Height);
  37.                 e.Graphics.DrawString(demo, font, Brushes.Black, boundsHeader, fmtNotTrimmed);
  38.  
  39.                 RectangleF boundsLeft = new RectangleF(boundsHeader.X, boundsHeader.Y, textCenterBounds, boundsHeader.Height);
  40.                 SizeF sizeLeft = e.Graphics.MeasureString(demo, font, boundsLeft.Size, fmtTrimmed);
  41.  
  42.                 e.Graphics.DrawRectangle(Pens.Red, boundsLeft.X, boundsLeft.Y, boundsLeft.Width, textSize.Height);
  43.                 e.Graphics.DrawString(demo, font, Brushes.Black, boundsLeft, fmtTrimmed);
  44.             }
  45.             finally {
  46.                 font.Dispose();
  47.                 fmtTrimmed.Dispose();
  48.                 fmtNotTrimmed.Dispose();
  49.             }
  50.         }
  51.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement