FleetL
FleetL

Reputation: 41

C# - How to draw shapes on bitmap from list?

I'm working on a paint-like program. There is a usercontrol subclass "SketchControl" which has a Sketch. Sketch in turn has a bitmap.

Previously, whenever a shape was drawn in the usercontrol, the shape would directly be drawn onto the bitmap. We have to change the program so that all forms are added to a list, "drawing", so that we can save the drawing. Now we have to draw the shapes from this list, but I'm unable to do so. Shapes have a paint method, "draw".

I have tried adding this or similar code to my SketchControl paint method and my Sketch paint method:

using (Graphics g = Graphics.FromImage(myBitmap))
            {
                for (int i = 0; i < drawing.Count; i++)
                {
                    drawing[i].draw(g);
                }
            }

which did not work.

"draw" for a particular shape might look like

public override void draw(Graphics gr)
         {  gr.DrawEllipse(pen, p1, p2); }

I apologize if this is a dumb question but I would really appreciate any help. How to get the shapes to turn op on the bitmap when I draw them from a list in stead of directly onto the bitmap? Where should my code be?

Upvotes: 2

Views: 1349

Answers (1)

Pribina
Pribina

Reputation: 780

can you check your saving of Graphics maybe or actual implementation of draw method? Here is functional drawing with output of picture

enter image description here

var drawing = new List<IDrawable>
{
    new AquaCircle(),
    new RedCircle(),
};
var imageFile = new Bitmap(200, 200);
using (var g = Graphics.FromImage(imageFile))
{
    for (var i = 0; i < drawing.Count; i++)
    {
        drawing[i].Draw(g);
    }
}

imageFile.Save("test.jpg");

shapes can implament interface

public interface IDrawable
{
    void Draw(Graphics g);
}

public class AquaCircle : IDrawable
{
    void IDrawable.Draw(Graphics g)
    {
        g.DrawEllipse(new Pen(Color.Aqua, 1), 1, 1, 100, 100);
    }
}

public class RedCircle : IDrawable
{
    void IDrawable.Draw(Graphics g)
    {
        g.DrawEllipse(new Pen(Color.Red, 1), 25, 25, 100, 100);
    }
}

Upvotes: 1

Related Questions