在表单上绘制圆圈

时间:2016-10-22 15:19:14

标签: c# winforms brush

我有一个WinForms应用程序,我想以编程方式在某些区域上绘制圆圈。我遇到了几个问题,任何见解都会受到赞赏!

1)我已经获得了绘制和清除圆圈的代码(见下文),但圆圈正在我的所有控件后面绘制。我希望他们被画成#34;最顶层"在每种情况下。我该怎么做?

2)当我的应用启动时,我会有一些需要立即绘制的圈子。我尝试在Form Load事件上绘制它们无济于事。但至于这里(Form graphics not set when form loads)我现在正在Paint事件上绘制它。虽然这种方法运行得相当好(有一个bool以确保它只是第一次这样做),但this.Invalidate();似乎有问题(因为没有绘制圆圈)。有没有更好的办法?这是我的代码(parseText在comboBox的索引更改上运行):

private void parseText()
{
    this.Invalidate();
    List<string> lines = new List<string>(richTextBoxRaw.Text.Split(new string[] { Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries));

    foreach (string s in lines)
    {
        switch (s)
        {
            case "<draw1>":
                drawCircle(107, 26, 25);
                break;
            default:
                break;
        }
    }
}

private void drawCircle(int x, int y, int transparency)
{
    if (transparency < 0)
        transparency = 0;
    else if (transparency > 255)
        transparency = 255;

    SolidBrush brush = new SolidBrush(Color.FromArgb(transparency, 255,0,0));
    Graphics graphics = this.CreateGraphics();

    graphics.FillEllipse(brush, new Rectangle(x, y, 25, 25));
    brush.Dispose();
    graphics.Dispose();
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
    if (starting)
        parseText();

    starting = false;
}

1 个答案:

答案 0 :(得分:2)

完成您的要求的一个不那么复杂但又有效的方法可能是创建自定义透明面板并将其放置在将绘制红色圆圈的控件之上。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void DrawCircle(int x, int y, int transparency, Graphics graphics)
    {
        if (transparency < 0)
            transparency = 0;
        else if (transparency > 255)
            transparency = 255;

        SolidBrush brush = new SolidBrush(Color.FromArgb(transparency, 255, 0, 0));

        graphics.FillEllipse(brush, new Rectangle(x, y, 25, 25));
        brush.Dispose();
        graphics.Dispose();
    }

    private void TransparentPanel1_Paint(object sender, PaintEventArgs e)
    {
        DrawCircle(10, 10, 255, e.Graphics);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        transparentPanel1.Enabled = false;
        transparentPanel1.Paint += TransparentPanel1_Paint;
        transparentPanel1.BringToFront();
    }
}

public class TransparentPanel : Panel
{
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
            return cp;
        }
    }
    protected override void OnPaintBackground(PaintEventArgs e)
    {
        //base.OnPaintBackground(e);
    }
}

enter image description here