UserPaint shortcut drawn text does not fit

I have a custom Label class, drawn text is not suitable. What am I doing wrong here?

class MyLabel: Label { public MyLabel() { SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true); } protected override void OnPaint(PaintEventArgs e) { using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, Color.Black, Color.LightGray, LinearGradientMode.ForwardDiagonal)) e.Graphics.DrawString(Text, Font, brush, ClientRectangle); } } 

If I set the MyLabel text as "123456790 123456790" ( AutoSize = true ), then I see in Designer (or at runtime) "1234567890 123456789" (without the last zero, but some space). If I try "1234567890 1234567890 1234567890 1234567890", then there will be "1234567890 1234567890 1234567890 12345678" (no "90", but again some space).

0
c # winforms labels ownerdrawn
source share
3 answers

Here we consider a solution (perhaps not the best) for the described problem, which can be rephrased as "Authorized label with the color of the gradient text."

 class MyLabel: Label { private bool _autoSize = true; /// <summary> /// Get or set auto size /// </summary> public new bool AutoSize { get { return _autoSize; } set { _autoSize = value; Invalidate(); } } public MyLabel() { SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true); base.AutoSize = false; } protected override void OnPaint(PaintEventArgs e) { // auto size if (_autoSize) { SizeF size = e.Graphics.MeasureString(Text, Font); if (ClientSize.Width < (int)size.Width + 1 || ClientSize.Width > (int)size.Width + 1 || ClientSize.Height < (int)size.Height + 1 || ClientSize.Height > (int)size.Height + 1) { // need resizing ClientSize = new Size((int)size.Width + 1, (int)size.Height + 1); return; } } using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, Color.Black, Color.LightGray, LinearGradientMode.ForwardDiagonal)) e.Graphics.DrawString(Text, Font, brush, ClientRectangle); } } 

The idea behind is very simple: redefine AutoSize and process it in the Paint event (all in one place), if the text size is required differs from ClientSize - resize (which will lead to redrawing). One thing is that you have to add +1 to the width and height, because SizeF has fractions, and it’s better to have +1 pixel more than lose 1 pixel, and your text is not suitable.

0
source share
 e.Graphics.DrawString(Text, Font, brush, ClientRectangle); 

You are using the wrong text rendering method. The Label class is automatically configured based on the return value of TextRenderer.MeasureText (). Therefore, you should use TextRenderer.DrawText () to get the same rendering result. You can also set the UseCompatibleTextRendering label property of the label to true, but this should not be your first choice.

+2
source share

Use Graphics.MeasureString to get the required bounding box size, and then set the size of the label surface to that size.

0
source share

All Articles