开发者

Double Buffering non-rectangular allocation

I draw on Panel in Windows.Forms.

When I use double buffering like here, I can allocate only rectangular area.

And when I draw circle or ellipse remaining space is filled with black color.

Please, help me figure out what I am doing wrong or how to cope with this problem.

Thanks in advance! :)

I tried this.DoubleBuffered = true to prevent from flicker. It is no use.

Var p is Panel to draw something on it.

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

    private void Dr(bool variant)
    {
        BufferedGraphicsContext currentContext;
        BufferedGraphics myBuffer;
        currentContext = BufferedGraphicsManager.Current;
        myBuffer = currentContext.Allocate(panel1.CreateGraphics(), panel1.DisplayRectangle);
        LinearGradientBrush lgb;
        if (variant) lgb = new LinearGradientBrush(new Point(0, 0), new Point(500, 500), Color.Red, Color.DarkRed);
        else lgb = new LinearGradientBrush(new Point(0, 0), new Point(500, 500), Color.DarkRed, Color.Red);
        myBuffer.Graphics.FillEllipse(lgb, 0, 0, 300, 300);
        myBuffer.Graphics.DrawString("Lorem ipsum", new Font("calibri", 40), Brushes.White, new PointF(50, 50));
        myBuffer.Render();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Dr(true);
    }

    private void panel1_MouseEnter(object sender, EventArgs e)
    {
    开发者_JAVA百科    Dr(false);
    }

    private void panel1_MouseLeave(object sender, EventArgs e)
    {
        Dr(true);
    }
}


Without commenting on what you are trying to do or what you may or may not potentially be doing wrong here, the basic problem is not flicker. Double buffering will not help. You have neglected to fill in any part of the panel you added to the buffer that you did not draw on. Add code such as:

Brush solidBrush = new SolidBrush(p.BackColor);
myBuffer.Graphics.FillRectangle(solidBrush, 0, 0, p.Width, p.Height);

This will fill the entire rect with the panels original back color.

However, that will fix your immediate issue but it still may not work like you want. Try moving a window over your form. As soon as the panel has to repaint itself for any reason, what you have drawn is gone. To make a panel with a persistent drawing on it you will have to create your own control, inherit from a Panel, and implement the custom drawing in the control's OnPaint method.

C# Winforms controls are not truly transparent, so if you want a transparent background you have to create your own control. The technique is described here:

https://web.archive.org/web/20141227200000/http://bobpowell.net/transcontrols.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜