Tuesday, May 27, 2008

Get Corners of a Rectangle, given the center,height and Width

Following code will draw a rectangle on a graphics context, when a valid center, height and width is provided.


int CenterX, CenterY;

public void DrawRect(Graphics g, int Width, int Height)

{

Point[] RectPts;

double Theta;

int HalfWidth, HalfHeight;

double Radius;

RectPts = new Point[4];

HalfWidth = Width / 2;

HalfHeight = Height / 2;

Radius = Math.Sqrt(HalfWidth * HalfWidth + HalfHeight * HalfHeight);

Theta = Math.Acos(HalfWidth / Radius);

RectPts[0] = GetPt(Theta, Radius);

RectPts[1] = GetPt(Math.PI - Theta,Radius);

RectPts[2] = GetPt(Math.PI + Theta,Radius);

RectPts[3] = GetPt(-Theta,Radius);

Pen PenColor = new Pen(Color.Red, 2);

g.DrawPolygon( PenColor, RectPts);

PenColor.Dispose();

}

private Point GetPt(double Offset, double Radius)

{

double tAngle;

Point temp = new Point();

double Rotation = 30;

tAngle = Rotation / 180 * Math.PI + Offset;

temp.X = CenterX + (int)(Radius * Math.Cos(tAngle));

temp.Y = CenterY + (int)(Radius * Math.Sin(tAngle));

return temp;

}

The code idea is copied from some site and converted to C# in a compilable and working format. Hope it helps.