Frage

I have been using mono for a short while and one of the issues I came upon was that loading an image into a CGImage object would end up with the image being flipped vertically. This was the code I was using originally:

public static CGImage LoadJPEG (string sImagePath, bool bSmoothImage)
{
    return CGImage.FromJPEG (
        new CGDataProvider (sImagePath), null, bSmoothImage,
        CGColorRenderingIntent.Default);
}

There's a PNG version to that where you simply use CGImage.FromPNG instead, but if you use the wrong format with the wrong file type then you'll get an exception. As I always know what my file types are I didn't put any catches/checks to prevent that exception.

You'll notice just using this code will flip the image vertically, I can't explain why mono does this and having a look at some of the solutions I wasn't looking forward to fixing it.

So how to flip it back? Well, luckily I can answer that myself, but I can't vouch for it being the "correct" way to do it!

War es hilfreich?

Lösung

Bare in mind that this is simply a quick fix for the image loading upside down. I think the code is about as simple as it can get while getting the job done.

public static CGImage RotateImage (CGImage oImage)
{
    CGContext oContext;
    UIImage oRotatedImage;
    RectangleF oImageBounds;
    //
    oImageBounds = new RectangleF (0, 0, oImage.Width, oImage.Height);
    //
    UIGraphics.BeginImageContext (oImageBounds.Size);
    oContext = UIGraphics.GetCurrentContext ();
    //
    oContext.DrawImage (oImageBounds, oImage);
    oRotatedImage = UIGraphics.GetImageFromCurrentImageContext ();
    UIGraphics.EndImageContext ();
    //
    return oRotatedImage.CGImage;
}

I stumbled upon this solution while playing around with the code in this question and thought, hey that works and I don't need it to do anything else :D So I hope this helps you!

Also, if anyone can explain the reasons for all this then please, I'd be interested to know what's actually going on. My only previous experience of working with 2D graphics is from using the XNA framework.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top