【问题标题】:Draw image without repainting surfaces from other controls无需从其他控件重新绘制表面即可绘制图像
【发布时间】:2016-04-08 17:38:11
【问题描述】:

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

Paint(object, PaintEventArgs)Hex 下我绘制图像:

e.Graphics.DrawImage(foo.Properties.Resources.h, ClientRectangle);

但它不断地从其他控件重新绘制表面:

我怎样才能避免这种情况?

HexMap的代码:http://pastebin.com/XsjKc3Yf

【问题讨论】:

  • 共享其余代码,例如控件的构造函数。不清楚你现在在问什么。当前图像的哪一部分是其他控件的重绘?您的控件是否负责绘制单个六边形?
  • CreateGraphics 几乎总是一个错误。使用容器的绘制事件并从那里使用 Graphic 对象。由于您的控件是重叠的,因此如果没有针对每个十六进制的控件,这会更好。
  • 不,我尝试了其他方法,但它显然不起作用。我有一些其他的线xD
  • 查看我的新答案;我误读了这个问题..
  • 您正在使用矩形进行绘画。您可能需要改用FillPolygon

标签: c# winforms graphics controls


【解决方案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();
    }
    

【讨论】:

  • 放弃 UserControls 你已经完全改变了前提。这可能对您有所帮助,如果您实际上不需要控件来单击或移动等,请务必使用它但肯定不会回答原始问题。
  • 对不起,如果我过于客观或刻薄。这个答案满足了这个问题。我对图形知之甚少,所以我保持最低限度。
猜你喜欢
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 2017-01-31
  • 1970-01-01
  • 2011-06-15
相关资源
最近更新 更多