为标签绘制抗锯齿椭圆区域

问题描述 投票:3回答:1

我为标签绘制了一个类似椭圆的区域,但我不知道如何设置它的抗锯齿。

片段:

Rectangle circle = new Rectangle(0, 0, labelVoto.Width,labelVoto.Height);
var path = new GraphicsPath();
path.AddEllipse(circle);
labelVoto.Region = new Region(path);

这就是结果:

enter image description here

有谁能够帮我?

c# winforms label drawing
1个回答
1
投票

设置SmoothingMode对象的Graphics。覆盖OnPaintBackground而不是改变Region。区域不支持抗锯齿。此示例通过从Label派生自定义标签来创建。

public class EllipticLabel : Label
{
    protected override void OnPaintBackground(PaintEventArgs e)
    {
        // This ensures that the corners of the label will have the same color as the
        // container control or form. They would be black otherwise.
        e.Graphics.Clear(Parent.BackColor);

        // This does the trick
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

        var rect = ClientRectangle;
        rect.Width--;
        rect.Height--;
        using (var brush = new SolidBrush(BackColor)) {
            e.Graphics.FillEllipse(brush, rect);
        }
    }
}

如果将绘制矩形大小设置为ClientRectangle。椭圆将被右边和底部的一个像素剪裁。因此我将其大小减小了一个像素。

您可以通过在代码或属性窗口中设置标签的BackColor属性来设置椭圆的所需背景颜色。

结果:

enter image description here

编译完代码后,自定义标签会自动显示在当前项目的Toolbox中。

© www.soinside.com 2019 - 2024. All rights reserved.