在WinForms C#中绘制实心圆

问题描述:

我有一个与连接交互的WinForms应用程序.如果连接正常,我想显示一个绿色的(一切都很好")实心圆,否则,我想要显示一个红色实心的圆.

I have a WinForms application that interacts with a connection. If the connection is fine I want to show a green ("everything is fine") filled circle, if not I want to show a red filled circle.

我在工具箱中没有找到任何圆形元素,因此我认为必须自己绘制.

I found no circle element in the toolbox so I think I have to draw it on my own.

我创建了一个名为 picBoxClientState 的图片框,并从此代码开始

I created a picture box called picBoxClientState and started with this code

public partial class FrmMain : Form
{
    public void CheckSignedInState()
    {
        // some other code

        DrawClientStateIcon(client.IsSignedIn);
    }

    private void DrawClientStateIcon(bool isSignedIn)
    {
        Point rectangleLocation = picBoxClientState.Location;
        Size rectangleSize = picBoxClientState.Size;
        Rectangle rectangle = new Rectangle(rectangleLocation, rectangleSize);

        Color iconColor = isSignedIn ? Color.Green : Color.Red;
        SolidBrush iconBrush = new SolidBrush(iconColor);

        Graphics graphics = picBoxClientState.CreateGraphics();
        graphics.FillEllipse(iconBrush, rectangle);
    }
}

每当我调用 CheckSignedInState()时,如何在此图片框上绘画?

How can I draw on this picturebox whenever I call CheckSignedInState() ?

也许有比绘制更好的方法了吗?(我不想切换两个图像,因为可能会绘制更多状态)

Maybe there is a better way instead of drawing? (I don't want to toggle two images because there might be more states to draw)

使用 Label 控件绘制椭圆的简单示例.
您可以使用具有 Paint事件的任何控件绘制形状.
它也可以是 Panel PictureBox Button ...

A simple example using a Label control to draw an ellipse.
You can use any control that has a Paint event to draw shapes.
It could also be a Panel, a PictureBox, a Button...

在类范围内声明的 bool 变量( clientIsSignedIn )用于跟踪当前状态,如您的 client.IsSignedIn 所报告的那样.>值.

A bool variable (clientIsSignedIn) declared at Class scope is used to keep track of the current status, as reported by your client.IsSignedIn value.

状态更改时,更新 clientIsSignedIn

When the status changes, update clientIsSignedIn and Invalidate() the Control that provides the visual aid.

bool clientIsSignedIn = false;

public void CheckSignedInState()
{
    // some other code
    clientIsSignedIn = client.IsSignedIn;
    lblVisualStatus.Invalidate();
}

private void lblVisualStatus_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.FillEllipse((clientIsSignedIn) ? Brushes.Green : Brushes.Red, ((Control)sender).ClientRectangle);
}