Drawing managed user text

class starbutton : UserControl
{
    [Bindable(true)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    [Browsable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public override string Text { get { return base.Text; } set { base.Text = value; this.Invalidate(); } }

    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics graphics = e.Graphics;
        SolidBrush brush2 = new SolidBrush(Color.Green);
        Point[] points =
        { 
            new Point(ClientSize.Width / 2, 0), 
            new Point(0, ClientSize.Height/4), 
            new Point(0, ClientSize.Height), 
            new Point(ClientSize.Width, ClientSize.Height)
        };
        graphics.FillPolygon(brush2, points);
        base.OnPaint(e);
    }
}

I created a user control to create a button using shapes. I managed to do this, but I added a property so that it can display text on the form, but not display text. Why doesn't he show the text?

enter image description here

+4
source share
2 answers

You draw a strange polygon in the implementation OnPaintand do not render any text.

Add code that displays the text (i.e. using TextRenderer.DrawText after drawing the polygon:

TextRenderer.DrawText(e.Graphics, Text , this.Font, 
    new Point(10, 10), SystemColors.ControlText);
+4
source

- .

:

  • Button ( , StartButton, Button, , Text)
  • Text
  • TextAlign, , , .
  • , , .
  • , , , .
  • .

:

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace MyUserControls
{
    public class StartButton : Button
    {
        public StartButton()
        {
            this.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.FlatAppearance.BorderSize = 0;
            this.BackColor = System.Drawing.Color.Green;
            this.TextAlign = System.Drawing.ContentAlignment.BottomLeft; 
            this.Size = new Size(100, 100); 
        }
        protected override void OnPaint(PaintEventArgs pevent)
        {
            this.UpdateRegion();
            base.OnPaint(pevent);
        }
        protected void UpdateRegion()
        {
            var path = new GraphicsPath();
            Point[] points =
            { 
                new Point(ClientSize.Width / 2, 0), 
                new Point(0, ClientSize.Height/4), 
                new Point(0, ClientSize.Height), 
                new Point(ClientSize.Width, ClientSize.Height)
            };
            path.AddPolygon(points);
            this.Region = new Region(path);
        }
    }
}

:

enter image description here

+2

Source: https://habr.com/ru/post/1606667/


All Articles