Drawing a filled ellipse doesn't appear

后端 未结 1 1682
失恋的感觉
失恋的感觉 2021-01-29 11:55

Trying to draw a pacman in c# using visual studio e started to drew the dots but i having some troubles i wrote this class to make the dots.

    public class dra         


        
相关标签:
1条回答
  • 2021-01-29 12:20

    There are two errors in your code:

    1 - This wa of drawing on a form or control is non-persistent; all drawing must either happen in a Paint event or be triggered from there. A good solution is to call the drawing code there and to hand down the e.Graphics of the Paint event as a parameter.

    2 - You use CreateGraphics and try to paint with that. The result would disappear anyway as soon as you e.g. minimze your window and restore it. But in reality nothing get shown in the first place. Why? Well, your draw blobs are an inner class and here the keyword thisrefers not to the form but to the draw class. So you create a Graphics for an invisible control (without a size and which is not part of the form) and, of course, nothing happens..

    If you want to have Drawing items they should

    • store their sizes, positions, states etc (in their constructor) and

    • have a drawing method which you can call from the outside and which gets handed a Graphics object they then draw themselves on..

    • they also should have a better name, like Dot or PacDot or the like..

    Here is a minimal version:

    // a list of all PacDots:
    public List<PacDot> theDots = new List<PacDot>();
    
    public class PacDot : System.Windows.Forms.Control
    {
        public PacDot(int x, int y, int w, int h)
        {
            Left = x; Top = y; Width = w; Height = h; 
        }
    
        public void Draw(Graphics G)
        {
          G.FillEllipse(Brushes.Brown, 
            new System.Drawing.Rectangle(Left, Top, Width,  Height));
        }
    }
    
    
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        foreach (PacDot dot in theDots) dot.Draw(e.Graphics);
    }
    
    // a test button:
    private void button1_Click(object sender, EventArgs e)
    {
        theDots.Add(new PacDot(30, 10, 5, 5));
        theDots.Add(new PacDot(30, 15, 5, 5));
        theDots.Add(new PacDot(15, 10, 5, 5));
        this.Invalidate();
    }
    

    PS: Since your draw class is indeed a Control descendent you could also add them to the Form with form1.Controls.Add(..); but they still will have to have a paint event, where they paint themselves..

    0 讨论(0)
提交回复
热议问题