在子控件上绘制图像

时间:2009-02-17 16:11:39

标签: c# winforms

我需要在面板上绘制一个包含一些子控件的图像。我不想让它隐藏在那些控件后面,这就是我在Paint事件中绘制图像时的情况。

以下是我用来覆盖面板OnPaint方法的代码:

protected override void OnPaint(PaintEventArgs e)
{
    try
    {
        base.OnPaint(e);
        //Draw icon for views at top right corner of the panel.
        e.Graphics.SmoothingMode = 
                System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        if (_viewButton != ViewButton.None)
        {
            Brush menuBrush = 
                new SolidBrush(_viewButton == ViewButton.Highlighted ? 
                    Color.Black : Color.Gray);
            e.Graphics.FillPolygon(menuBrush, new Point[] { 
                new Point(this.Width - 29, 03), 
                new Point(this.Width - 19, 03), 
                new Point(this.Width - 24, 09) });
            menuBrush.Dispose();

            //Draw border of the panel.
            Rectangle borderRect = 
                    new Rectangle(0, 0, this.Width - 1, this.Height - 1);
            GraphicsPath borderPath = GetRoundPath(borderRect, 8);
            e.Graphics.DrawPath(new Pen(Color.LightGray), borderPath);
        }
    }
    catch (Exception ex)
    {
        throw new IDSException(ex);
    }
}

protected override void OnPaint(PaintEventArgs e)
{
    try
    {
        base.OnPaint(e);
        //Draw icon for views at top right corner of the panel.
        e.Graphics.SmoothingMode = 
                System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        if (_viewButton != ViewButton.None)
        {
            Brush menuBrush = 
                new SolidBrush(_viewButton == ViewButton.Highlighted ? 
                    Color.Black : Color.Gray);
            e.Graphics.FillPolygon(menuBrush, new Point[] { 
                new Point(this.Width - 29, 03), 
                new Point(this.Width - 19, 03), 
                new Point(this.Width - 24, 09) });
            menuBrush.Dispose();

            //Draw border of the panel.
            Rectangle borderRect = 
                    new Rectangle(0, 0, this.Width - 1, this.Height - 1);
            GraphicsPath borderPath = GetRoundPath(borderRect, 8);
            e.Graphics.DrawPath(new Pen(Color.LightGray), borderPath);
        }
    }
    catch (Exception ex)
    {
        throw new IDSException(ex);
    }
}

2 个答案:

答案 0 :(得分:1)

Paint event(或OnPaint method的覆盖)是执行此类操作的错误位置,因为您需要确保最后调用您的绘图例程。

相反,如果您有权访问父控件,请覆盖OnPaint方法,然后调用基本实现。 然后绘制您的图片,它将被绘制在其他所有图像之上。

答案 1 :(得分:0)

执行此操作的最佳方法是在图像上使用BringToFront()方法。

它会在所有控件上绘制图像。 但是,除非控件全部位于同一父控件上,否则这将不起作用。