Light-weight winform graphic element substitute of

2019-07-27 03:12发布

问题:

I am interested in creating a drawing element that is super-light weight. Such that I can create millions of these objects without the over-head that is associated with the System.Windows.Forms.Control class.

The class in question would inherit from the System.ComponentModel.Component class, and have (I am guessing) only a constructor and a paint(object sender, PaintEventArgs e) method. However, I don't know, how the System.Windows.Forms.Control class performs or facilitates the actual onscreen drawing.

How could I replicate the paint/drawing function with a valid drawing context, similar to the System.Windows.Forms.Control class?

回答1:

Millions of controls would be a memory-hog, however light-weight your control may be. What I'd do in this situation is to create a single control that performs drawing operations (and inherits from System.Windows.Forms.Control) and a class say MyDrawingObject that keeps necessary data for those each instance of those millions of objects. The drawing class will then have a collection (List, Array or something) of those MyDrawingObjects and would draw them on the fly.

Suppose your drawing objects are balls with different radius, color, position and weight. My Ball class would be something like:

class Ball
{
    public float Radius {get; set;}
    public int Color {get; set;}
    public float Weight {get; set;}
    public Point Position {get; set;}

    ...
}

Now my Control would be something like:

class MyDrawingBoard : System.Windows.Forms.Control
{
    List<Ball> MyBalls = new List<Ball>();

    override void OnPaint(object sender, PaintEventArgs e)
    {
         foreach(var b in MyBalls)
         {
             e.Graphics.DrawEllipse()...
         }
    }
}

You can further improve performance by drawing only those objects that intersect with the ClipRectangle, or even going to the extent of managing multiple Lists for different kinds of objects. That all depends upon your needs and the objectives of your application.