In System.Drawing
and System.Drawing.Drawing2D
, I can only draw horizontal or vertical shape. Now i want to draw custom shape.
Given the coordinate of points A, B, C, D. I want to draw an ellipse like the blue one in the picture.
In System.Drawing
and System.Drawing.Drawing2D
, I can only draw horizontal or vertical shape. Now i want to draw custom shape.
Given the coordinate of points A, B, C, D. I want to draw an ellipse like the blue one in the picture.
The example below is taken from MSDN:
private void RotateTransformAngle(PaintEventArgs e)
{
// Set world transform of graphics object to translate.
e.Graphics.TranslateTransform(100.0F, 0.0F);
// Then to rotate, prepending rotation matrix.
e.Graphics.RotateTransform(30.0F);
// Draw rotated, translated ellipse to screen.
e.Graphics.DrawEllipse(new Pen(Color.Blue, 3), 0, 0, 200, 80);
}
The correct solution involves:
Graphics.TranslateTransform
to move the center to the originSize
and the Location
of the bounding Rectangle
Graphics.RotateTransform
to rotate the canvasGraphics.DrawEllipse
Graphcis
objectThis does take a little Math
but will produce real and fine ellipses..
For fun you also may want to play with a cheap, fake solution: I uses the DrawClosedCurve
method with a tension.
To test I added a TrackBar
set with a Maximum
of 100
.
Values of around 80, i.e. Tensions
of around 0.8f
create pretty nice ellipsoids:
private void panel1_Paint(object sender, PaintEventArgs e)
{
List<Point> points1 = new List<Point>()
{ new Point(300, 100), new Point(500, 300), new Point(400, 500), new Point(200, 300) };
List<Point> points2 = new List<Point>()
{ new Point(100, 100), new Point(500, 100), new Point(500, 400), new Point(100, 400) };
e.Graphics.DrawClosedCurve(Pens.Red, points1.ToArray(),
(float)(trackBar1.Value / 100f), System.Drawing.Drawing2D.FillMode.Alternate);
e.Graphics.DrawClosedCurve(Pens.Blue, points2.ToArray(),
(float)(trackBar1.Value / 100f), System.Drawing.Drawing2D.FillMode.Alternate);
}