Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw mirrored in C# using System.Drawing.Graphics

I have written a little helper function which performs some sort of drawing operations, which are rather complex.

I call this function out of another class which sometimes applies transformations to it. Rotating and translating works fine, but now I want to force the helper function to draw the whole thing mirrored over the y-axis.

I tried to use

g.ScaleTransform(0, -1);

before calling the helper function, but it threw an exception.

So, how is it possible to draw mirrored using a System.Drawing.Graphics object?

like image 977
Emiswelt Avatar asked Aug 06 '11 09:08

Emiswelt


2 Answers

You need to call

g.ScaleTransform(1, -1);

Note that now your image will be drawn behind the upper screen edge. To fix it, you need to call g.TranslateTransform before g.ScaleTransform:

g.TranslateTransform(0, YourImageHeightHere);
g.ScaleTransform(1, -1);
like image 101
max Avatar answered Sep 25 '22 23:09

max


This is how it's done with a BitMap, you can draw the image from the graphics and redraw the graphics object with the modified one.

    public Bitmap MirrorImage(Bitmap source)
    {
        Bitmap mirrored = new Bitmap(source.Width, source.Height);
        for(int i = 0; i < source.Height; i++)
            for(int j = 0; j < source.Width; j++)
                mirrored.SetPixel(i, j, source.GetPixel(source.Width - j - 1, i);
        return mirrored;
    }

Edit: @MattSlay, thanks it was a typo, I fixed it.

like image 23
MrFox Avatar answered Sep 26 '22 23:09

MrFox