Search code examples
c#iosxamarin.iosavfoundationios-camera

Turn camera picture depending on the device orientation (Xamarin.iOS)


I want to make a Xamarin.iOS app where I can capture pictures like the camera... My app supports only portrait.

I want to turn the captured picture to portrait if the camera was landscape when i capture the picture.

Does someone know how I can do this?

Code

    public async void CapturePhoto()
    {

        var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
        var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);

        var jpegImageAsBytes = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer).ToArray();

        string base64StringImage = Convert.ToBase64String(jpegImageAsBytes);

        FaceRecognition faceRecognition = new FaceRecognition();
        int result = faceRecognition.SendPhoto(base64StringImage);
     } 

Solution

  • Try this :

    var currentOrientation = UIApplication.SharedApplication.StatusBarOrientation;
    
    if (currentOrientation == UIInterfaceOrientation.Portrait)
    {
        videoConnection.VideoOrientation = AVCaptureVideoOrientation.Portrait;
    }
    else if (currentOrientation == UIInterfaceOrientation.LandscapeRight)
    {
        videoConnection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight;
    }
    //xxx
    

    Update:

    If the app only supports an orientation or you lock the screen , there is another old way to detect device orientation. Core Motion

    public void LockOrientation()
    {
        CMMotionManager CMManager = new CMMotionManager();
        CMManager.DeviceMotionUpdateInterval = 0.2f;
        CMManager.StartDeviceMotionUpdates(NSOperationQueue.MainQueue, (motion, error) => {
            if (Math.Abs(motion.Gravity.X) > Math.Abs(motion.Gravity.Y))
            {
                Console.WriteLine("Lan");
                if (motion.Gravity.X > 0)
                {
                    UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeLeft), new NSString("orientation"));
                    Console.WriteLine("Left");
                }
                else
                {
                    UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeRight), new NSString("orientation"));
                    Console.WriteLine("Right");
                }
            }
            else
            {
                if (motion.Gravity.Y >= 0)
                {
                    Console.WriteLine("Down");
                }
                else
                {
                    Console.WriteLine("UP");
                }
            }
    
            CMManager.StopDeviceMotionUpdates();
        });
    }
    

    Refer to here