Home > Net >  DrawEllipse on Bitmap and return the Bitmap with the ellipse on it
DrawEllipse on Bitmap and return the Bitmap with the ellipse on it

Time:09-29

I am using a Graphics to draw an Ellipse and I want to return a Bitmap that contains that ellipse. Does my code make sense?

    private static Graphics ChipCanvas = Graphics.FromImage(new Bitmap(60, 60));
    
    public override Bitmap GetImage()
            {
              
                if (Color == PieceColors.Black)
                    ChipCanvas.FillEllipse(Brushes.Black, 0, 0, 5, 5);
                else
                    ChipCanvas.FillEllipse(Brushes.White, 0, 0, 5, 5);
    
                

                return new Bitmap(60, 60, ChipCanvas);
            }

CodePudding user response:

No, it doesn't. Graphics objects are not persistent canvases. They draw and forget. The bitmap is the canvas.

Try it like this:

private Bitmap bitmap = new Bitmap(60, 60);

public Bitmap GetImage()
{
  using (var g = Graphics.FromImage(bitmap))
  {
    g.SmoothingMode = SmoothingMode.AntiAlias;
    g.FillEllipse(Brushes.Black, 0, 0, 5, 5);
  }
  return bitmap;
}
  • Related