解决C# WinForm Graphics绘制闪烁问题

不直接使用form的CreateGraphics创建Graphics进行绘制,可以先在Form上面放一个需要大小的PictureBox,再创建一个同大小的Bitmap,将这个Bitmap设置为PictureBox的Image。再在这个Bitmap上进行绘制,这样拖动resize之类就不会闪烁了。

代码片段:

PictureBox ImageBox = null;
Bitmap RenderTarget = null;

Size RenderSize = new Size();
public RenderForm()
        {
            InitializeComponent();

            ImageBox = new PictureBox();
            ImageBox.Size = Properties.Resources.background.Size;
            ImageBox.Parent = this;

            renderSize = new Size(StatTools.Properties.Resources.background.Width, StatTools.Properties.Resources.background.Height);
        }


public Size renderSize
        {
            get { return RenderSize; }
            set
            {
                if(RenderTarget == null || RenderTarget.Width != value.Width || RenderTarget.Height != value.Height)
                {
                    RenderTarget = null;
                    RenderTarget = new Bitmap(value.Width, value.Height);

                    ImageBox.Size = new Size(value.Width, value.Height);
                    ImageBox.Image = RenderTarget;
                }

                RenderSize = value;
            }
        }

private void RenderForm_Paint(object sender, PaintEventArgs e)
        {
            if( CurrentRender != null )
            {
                var GFX = Graphics.FromImage(RenderTarget);
                CurrentRender.OnDraw(GFX, renderSize.Width, renderSize.Height);
            }
        }

 

posted @ 2016-11-13 12:23  bodong  阅读(2481)  评论(0编辑  收藏