I am drawing a graph on a control, but 0,0 is at the top-left hand corner of the control. Is there a way to flip the coordinates so that 0,0 is at the lower left corner of the control?
No, but using the Size
(or Height
) properties of the control, it is easy to calculate flipped coordinates: Just draw to Height-y
.
Not that I know of but if you use (x,Control.Height-y) you get the same effect.
in short no, however if i am drawing on controls a lot i have a few functions that help me:
Point GraphFromRaster(Point point) {...}
Point RasterFromGraph(Point point) {...}
this way i keep all the conversion in one place, no worrying about things like y - this.Height
scattered about the code.
If you are using WinForms, then you might find that you can flip the Y-Axis using Graphics.ScaleTransform:
private void ScaleTransformFloat(PaintEventArgs e)
{
// Begin graphics container
GraphicsContainer containerState = e.Graphics.BeginContainer();
// Flip the Y-Axis
e.Graphics.ScaleTransform(1.0F, -1.0F);
// Translate the drawing area accordingly
e.Graphics.TranslateTransform(0.0F, -(float)Height);
// Whatever you draw now (using this graphics context) will appear as
// though (0,0) were at the bottom left corner
e.Graphics.DrawRectangle(new Pen(Color.Blue, 3), 50, 0, 100, 40);
// End graphics container
e.Graphics.EndContainer(containerState);
// Other drawing actions here...
}
Note that I haven't tested this, but the documentation doesn't suggest passing a negative scaling factor is invalid.
You only need to include the begin/end container calls if you want to do additional drawing using the regular coordinate system as well. More information on graphics containers is available on MSDN.
Here's a simple UserControl that demonstrates how to do this:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.ScaleTransform(1.0F, -1.0F);
e.Graphics.TranslateTransform(0.0F, -(float)Height);
e.Graphics.DrawLine(Pens.Black, new Point(0, 0), new Point(Width, Height));
base.OnPaint(e);
}
}