绘制图像而不重新绘制其他控件的表面

时间:2016-04-08 17:38:11

标签: c# winforms graphics controls

我有一个透明图像可以在名为Hex的控件上绘制。我在Form1上持有它,并有一个名为Map的生成器。

Paint(object, PaintEventArgs)的{​​{1}}下,我绘制了图片:

Hex

但它不断重绘其他控件的表面:

enter image description here

我该如何避免这种情况?

代码为e.Graphics.DrawImage(foo.Properties.Resources.h, ClientRectangle); Hexhttp://pastebin.com/XsjKc3Yf

1 个答案:

答案 0 :(得分:-1)

我经历过最简单的方式:

  • 使Hex成为特殊课程。

    public class Hex
    {
        public Point Location;
        public Country Holder;
    
        public Hex(Country holder = null)
        {
            Holder = holder;
        }
    
        public void DrawMe(Graphics g)
        {
            g.DrawImage(Middle_Ages_Country.Properties.Resources.h, new Rectangle(Location, new Size(40, 40)));
        }
    }
    
  • 编辑了Map类,并创建了一个新方法DrawHexes,必要时会调用该方法。还使用了缓冲图形,因为它需要一些时间来绘制它们。

    public Map(int rows, int columns, Form1 owner)
    {
        int x = 40, y = 40;
        // Create map
        for (int row = 0; row < rows; row++)
        {
            List<Hex> r = new List<Hex>();
            for (int column = 0; column < columns; column++)
            {
                Hex h = new Hex(null)
                {
                    Location = new System.Drawing.Point(x, y),
                };
                r.Add(h);
                x += 40;
            }
            Grid.Add(r);
            x -= columns * 40;
            x = (row % 2) * 20 + 20;
            y += 30;
        }
    }
    
    public void DrawHexes(Form1 owner)
    {
        BufferedGraphicsContext context = BufferedGraphicsManager.Current;
        BufferedGraphics buf = context.Allocate(owner.CreateGraphics(), owner.ClientRectangle);
    
        buf.Graphics.Clear(Color.Red);
    
        foreach (List<Hex> row in Grid)
        {
            foreach (Hex h in row) h.DrawMe(buf.Graphics);
        }
        buf.Render();
    }