Question

I want the origin to be at the center of my window.

______________
|     ^      |
|     |      |
|     o----->|
|            |
|____________|

.NET wants it to be in the top left hand corner.

_____________>
|            |
|            |
|            |
|            |
V____________|

Dot net and I are trying to get along..

Does anyone know how to do this in C# just using the Graphics object?

Graphics.TranslateTransform doesn't do it since it leaves the coordinates flipped upside down. Combining this Graphics.ScaleTransform(1,-1) isn't satisfactory either since that makes text appear upside down.

Was it helpful?

Solution

One solution would be to use the TranslateTransform property. Then, instead of using the Point/PointF structs you could create a FlippedPoint/FlippedPointF structs of your own that have implicit casts to Point/PointF (but by casting them the coords get flipped):

public struct FlippedPoint
{
    public int X { get; set; }
    public int Y { get; set; }

    public FlippedPoint(int x, int y) : this()
    { X = x; Y = y; }

    public static implicit operator Point(FlippedPoint point)
    { return new Point(-point.X, -point.Y); }

    public static implicit operator FlippedPoint(Point point)
    { return new FlippedPoint(-point.X, -point.Y); }
}

OTHER TIPS

You can continue using ScaleTransform(1, -1) and reset the current transformation temporarily while drawing your text:

// Convert the text alignment point (x, y) to pixel coordinates
PointF[] pt = new PointF[] { new PointF(x, y) };
graphics.TransformPoints(CoordinateSpace.Device, CoordinateSpace.World, pt);

// Revert transformation to identity while drawing text
Matrix oldMatrix = graphics.Transform;
graphics.ResetTransform();

// Draw in pixel coordinates
graphics.DrawString(text, font, brush, pt[0]);

// Restore old transformation
graphics.Transform = oldMatrix;

Try creating the graphics object with a negative height. I don't know the C# library specifically, but this trick works in recent versions of GDI.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top