Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
60 views
in Technique[技术] by (71.8m points)

c# - Translucent circular Control with text

I am working on a project wherein I need to add a Control with the shape of a Circle with some text in the middle.
My problem is the circle is too small, when I resize it, it overlaps other controls. I want to draw the circle same width as the square.
Otherwise. how can I make the Control's background transparent?

enter image description here

I am using the code below:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    using (Bitmap bitmap = new Bitmap(this.Width, this.Height))
    {
        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.Clear(this.BackColor);

            using (SolidBrush brush = new SolidBrush(this._FillColor))
            {                      
                graphics.FillEllipse(brush, 0x18 - 6, 0x18 - 6, (this.Width - 0x30) + 12, (this.Height - 0x30) + 12);
            }

            Brush FontColor = new SolidBrush(this.ForeColor);
            SizeF MS = graphics.MeasureString(Convert.ToString(Convert.ToInt32((100 / _Maximum) * _Value)), Font);
            graphics.DrawString(Convert.ToString(Convert.ToInt32((100 / _Maximum) * _Value)), Font, FontColor, Convert.ToInt32((Width / 2 - MS.Width / 2) + 2), Convert.ToInt32((Height / 2 - MS.Height / 2) + 3));
            bitmap.MakeTransparent(this.BackColor);
            e.Graphics.DrawImage(bitmap, 0, 0);

            graphics.Dispose();
            bitmap.Dispose();
        }
    }
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a Custom Control derived from Control, which can be made translucent.
The interface is a colored circle which can contain a couple of numbers.

The Control exposes these custom properties:

Opacity: The level of opacity of the control BackGround [0, 255]
InnerPadding: The distance between the inner rectangle, which defines the circle bounds and the control bounds.
FontPadding: The distance between the Text and the Inner rectangle.

Transparency is obtained overriding CreateParams, then setting ExStyle |= WS_EX_TRANSPARENT;

The Control.SetStyle() method is used to modify the control behavior, adding these ControlStyles:

? ControlStyles.Opaque: prevents the painting of a Control's BackGround, so it's not managed by the System. Combined with CreateParams to set the Control's Extended Style to WS_EX_TRANSPARENT, the Control becomes completely transparent.

? ControlStyles.SupportsTransparentBackColor the control accepts Alpha values for it's BackGround color. Without also setting ControlStyles.UserPaint it won't be used to simulate transparency. We're doing that ourselves with other means.


To see it at work, create a new Class file, substitute all the code inside with this code preserving the NameSpace and build the Project/Solution.
The new Custom Control will appear in the ToolBox. Drop it on a Form. Modify its custom properties as needed.

A visual representation of the control:

WinForms Translucent Label

Note and disclaimer:

  • This is a prototype Control, the custom Designer is missing (cannot post that here, too much code, also connected to a framework).
    As presented here, it can be used to completely overlap other Controls in a Form or other containers. Partial overlapping is not handled in this simplified implementation.
  • The Font is hard-coded to Segoe UI, since this Font has a base-line that simplifies the position of the text in the middle of the circular area.
    Other Fonts have a different base-line, which requires more complex handling.
    See: TextBox with dotted lines for typing for the base math.

using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Windows.Forms;

[DesignerCategory("Code")]
class RoundCenterControl : Control, INotifyPropertyChanged, ISupportInitialize
{
    private const int WS_EX_TRANSPARENT = 0x00000020;
    private readonly int internalFontPadding = 10;
    private bool initializing = false;
    private Font m_CustomFont = null;
    private Color m_BackGroundColor;
    private int m_InnerPadding = 0;
    private int m_FontPadding = 20;
    private int m_Opacity = 128;

    public event PropertyChangedEventHandler PropertyChanged;

    public RoundCenterControl() => InitializeComponent();

    private void InitializeComponent()
    {
        SetStyle(ControlStyles.Opaque |
                 ControlStyles.SupportsTransparentBackColor |
                 ControlStyles.ResizeRedraw, true);
        SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
        BackColor = Color.LimeGreen;
        ForeColor = Color.White;
    }

    protected override CreateParams CreateParams {
        get {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= WS_EX_TRANSPARENT;
            return cp;
        }
    }

    public new Font Font
    {
        get => m_CustomFont;
        set {
            m_CustomFont = value;
            if (initializing) return;
            FontAdapter(m_CustomFont, DeviceDpi);
            NotifyPropertyChanged();
        }
    }

    public override string Text {
        get => base.Text;
        set { base.Text = value;
              NotifyPropertyChanged();
        }
    }

    public int InnerPadding {
        get => m_InnerPadding;
        set {
            m_InnerPadding = value;
            if (initializing) return;
            m_InnerPadding = (int)ValidateRange(value, 0, ClientRectangle.Height - internalFontPadding);
            NotifyPropertyChanged();
        }
    }

    public int FontPadding {
        get => m_FontPadding;
        set {
            m_FontPadding = value;
            if (initializing) return;
            m_FontPadding = (int)ValidateRange(value, internalFontPadding, ClientRectangle.Height - internalFontPadding);
            FontAdapter(m_CustomFont, DeviceDpi);
            NotifyPropertyChanged();
        }
    }

    public int Opacity {
        get => m_Opacity;
        set { m_Opacity = (int)ValidateRange(value, 0, 255);
              UpdateBackColor(m_BackGroundColor);
              NotifyPropertyChanged();
        }
    }

    public override Color BackColor {
        get => this.m_BackGroundColor;
        set {
            UpdateBackColor(value);
            NotifyPropertyChanged();
        }
    }

    private void NotifyPropertyChanged([CallerMemberName] string PropertyName = null)
    {
        Parent?.Invalidate(Bounds, true);
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
    }


    protected override void OnPaint(PaintEventArgs e)
    {
        using (var format = new StringFormat(
            StringFormatFlags.LineLimit | StringFormatFlags.NoWrap, 
            CultureInfo.CurrentUICulture.LCID))
        {
            format.LineAlignment = StringAlignment.Center;
            format.Alignment = StringAlignment.Center;
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

            using (var circleBrush = new SolidBrush(m_BackGroundColor))
            using (var foreBrush = new SolidBrush(ForeColor))
            {
                FontAdapter(m_CustomFont, e.Graphics.DpiY);
                RectangleF rect = InnerRectangle();
                e.Graphics.FillEllipse(circleBrush, rect);
                e.Graphics.DrawString(Text, m_CustomFont, foreBrush, rect, format);
            };
        };
    }

    private RectangleF InnerRectangle()
    {
        var minMax = GetMinMax(ClientRectangle.Height, ClientRectangle.Width);
        var size = new SizeF(minMax.min - m_InnerPadding,
                             minMax.min - m_InnerPadding);
        var position = new PointF((ClientRectangle.Width - size.Width) / 2,
                                  (ClientRectangle.Height - size.Height) / 2);
        return new RectangleF(position, size);
    }

    private void FontAdapter(Font font, float Dpi)
    {
        RectangleF rect = InnerRectangle();
        float size = (rect.Height - m_FontPadding) * (72.0f / Dpi) - internalFontPadding;
        int fontSize = (int)ValidateRange(size, 6, size);

        m_CustomFont = new Font(font.FontFamily, fontSize, font.Style, GraphicsUnit.Pixel);
    }

    private void UpdateBackColor(Color color)
    {
        m_BackGroundColor = Color.FromArgb(m_Opacity, Color.FromArgb(color.R, color.G, color.B));
        base.BackColor = m_BackGroundColor;
    }

    private float ValidateRange(float Value, float Min, float Max)
        => Math.Max(Math.Min(Value, Max), Min); //(Value < Min) ? Min : ((Value > Max) ? Max : Value);

    private (float min, float max) GetMinMax(float value1, float value2) 
        => (Math.Min(value1, value2), Math.Max(value1, value2));

    public void BeginInit() => initializing = true;

    public void EndInit()
    {
        initializing = false;
        Font = new Font("Segoe UI", 50, FontStyle.Regular, GraphicsUnit.Pixel);
        FontPadding = m_FontPadding;
        InnerPadding = m_InnerPadding;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...