如何基于动态值填充面板背景色 [英] How to fill panel background color based on dynamic value

查看:95
本文介绍了如何基于动态值填充面板背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#开发一个桌面应用程序,该应用程序需要使用动态值填充面板背景.例如,如果宽度为200px的面板和progress属性当前达到50%,则该面板的100px应该具有绿色其余颜色保持100px不变.

I am working on an desktop application in C# that requires a panel background to be filled using dynamic values.For example if the panel of width 200px and the progress property is currently reached at 50% then 100px of the panel should have green color in it rest 100px will be as it.

推荐答案

这是完成任务的简单控件

here's a simple control that does the job

public partial class ProgressPanel : Panel
{
    private float m_progress = 0;
    private Color m_progressColor = Color.Green;
    public ProgressPanel()
    {
        InitializeComponent();
    }

    /// <summary>
    /// the progress value is between 0 & 100 inclusively
    /// </summary>
    public float Progress
    {
        get
        {
            return m_progress;
        }
        set
        {
            m_progress = value;
            this.Invalidate();
        }
    }

    public Color ProgressColor
    {
        get
        {
            return m_progressColor;
        }
        set
        {
            m_progressColor = value;
            this.Invalidate();
        }
    }

    private void ProgressPanel_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.Clear(BackColor);

        e.Graphics.FillRectangle(new SolidBrush(ProgressColor), new Rectangle(new Point(), new Size((int)(Width * Progress / 100), Height)));
    }

    private void InitializeComponent()
    {
        this.SuspendLayout();
        // 
        // ProgressPanel
        // 
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.ProgressPanel_Paint);
        this.ResumeLayout(false);

    }
}

只需在您的项目中创建一个新的空类&将其命名为 ProgressPanel ,然后将上面的代码复制到其中.

just create a new empty class in your project & name it ProgressPanel then copy the above code into it.

现在,您可以使用新创建的 ProgressPanel ,就像您可以使用设计器中的其他任何控件一样

now you can use your newly created ProgressPanel as you would use any other control from the designer

请注意,此示例是一个简化的示例.您可能会注意到有些闪烁,但除此之外,它完全可以正常工作

note that this example is a simplified one. you may notice some flickering, but other than this it's totally functional

如果您想知道如何将此示例升级为专业控件,我很乐意提供帮助

if you want to know how to upgrade this example to a professional control, I'd be happy to help

这篇关于如何基于动态值填充面板背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆