0
votes

So - I have an app taking a picture with AVCaptureSession. I have an AVCapturePhoto - I want to end up with a uiImage in the correct orientation, which seems astonishingly hard to do. In portrait, I'm currently doing the following to correct the orientation:

    UIImage toImage( AVCapturePhoto photo )
    {
        return new UIImage(photo.CGImageRepresentation, 1, UIImageOrientation.Right);
    }

which works great - however, I can't find any way to detect if the phone is being held in landscape. Suppose for instance you have the orientation lock onto portrait - everything I query, such as the camera, the device current orientation - the UIApplication shared statusbarorientation, or whatever - returns portrait - but clearly the picture is actually turning up as a landscape image. I've looked at other answers, which say use "UIdevce.current.orientation" - but that always turns up "unknown" for me.

is there anyway of knowing the orientation of the camera, regardless of orientation lock, or otherwise turning up with a UIImage that is always the correct orientation - ie matches the real world?

1
One raw way to test it is to generate the device orientation notification and attach an observer to it, using the old good UIDevice.current.beginGeneratingDeviceOrientationNotifications(). In the observer for UIDevice.orientationDidChangeNotification you can detect the actual device orientation and behave accordingly on the image rotation. Hope it helpsLuca Iaco

1 Answers

0
votes

ok - so I found a hacky way to do it - reading the accelerometer - this seems to work:

UIAccelerometer.SharedAccelerometer.Acceleration += SharedAccelerometer_Acceleration;

...


private void SharedAccelerometer_Acceleration(object sender, UIAccelerometerEventArgs e)
{
    var roundedX = Math.Round(e.Acceleration.X);
    var roundedY = Math.Round(e.Acceleration.Y);
    UIImageOrientation orientation;
    if (Math.Abs(roundedX) < Math.Abs(roundedY))
        orientation = (roundedY == -1) ? UIImageOrientation.Right : UIImageOrientation.Left;
    else
        orientation = (roundedX == -1) ? UIImageOrientation.Down : UIImageOrientation.Up ;
    _currentOrientation = orientation;
}

...

return new UIImage(photo.CGImageRepresentation, 1, _currentOrientation);

However that can't be the "correct" way - it really surprises me that this is difficult - it seems that 100% of the time people would want whatever comes out of the camera to match whatever's in the real world? Would still love someone to tell me the right way of doing it!