# Code Snippets #20 - DrawEllipse

Published 8/1/2013 by createdbyx in Code Snippets | Programming
Tags: ,

Source (converted from C++) -> http://www.dailyfreecode.com/Code/draw-ellipse-midpoint-ellipse-algorithm-714.aspx

```/// <summary>
/// Draws a Ellipse.
/// </summary>
/// <param name="image">
/// The destination image.
/// </param>
/// <param name="centerX">
/// The x center position of the circle.
/// </param>
/// <param name="centerY">
/// The y center position of the circle.
/// </param>
/// <param name="width">
/// The width of the Ellipse.
/// </param>
/// <param name="height">
/// The height of the Ellipse.
/// </param>
/// <param name="color">
/// The color to use.
/// </param>
public static void DrawEllipse<T>(this GenericImage<T> image, int centerX, int centerY, int width, int height, T color)
{
// source (converted from C++) -> http://www.dailyfreecode.com/Code/draw-ellipse-midpoint-ellipse-algorithm-714.aspx
float aa = (width * width);
float bb = (height * height);
float aa2 = (aa * 2);
float bb2 = (bb * 2);

float x = 0;
float y = height;

float fx = 0;
float fy = (aa2 * height);

float p = (int)(bb - (aa * height) + (0.25 * aa) + 0.5);

image[(int)(centerX + x), (int)(centerY + y)] = color;
image[(int)(centerX + x), (int)(centerY - y)] = color;
image[(int)(centerX - x), (int)(centerY - y)] = color;
image[(int)(centerX - x), (int)(centerY + y)] = color;

while (fx < fy)
{
x++;
fx += bb2;

if (p < 0) p += (fx + bb);

else
{
y--;
fy -= aa2;
p += (fx + bb - fy);
}

image[(int)(centerX + x), (int)(centerY + y)] = color;
image[(int)(centerX + x), (int)(centerY - y)] = color;
image[(int)(centerX - x), (int)(centerY - y)] = color;
image[(int)(centerX - x), (int)(centerY + y)] = color;
}

p = (int)((bb * (x + 0.5) * (x + 0.5)) + (aa * (y - 1) * (y - 1)) - (aa * bb) + 0.5);

while (y > 0)
{
y--;
fy -= aa2;

if (p >= 0) p += (aa - fy);

else
{
x++;
fx += bb2;
p += (fx + aa - fy);
}

image[(int)(centerX + x), (int)(centerY + y)] = color;
image[(int)(centerX + x), (int)(centerY - y)] = color;
image[(int)(centerX - x), (int)(centerY - y)] = color;
image[(int)(centerX - x), (int)(centerY + y)] = color;
}
}```

• Comment
• Preview

# Created by: X

## Just another personal website in this crazy online world

 Dean Lunz (aka Created by: X) Computer programming nerd, and tech geek. About Me -- Resume