question

hosseintavakoli-7723 avatar image
0 Votes"
hosseintavakoli-7723 asked hosseintavakoli-7723 edited

Xamarin forms get device sensor rotation (orientation)

I have a Xamarin forms application, when I take picture with that picture not rotated for showing on PC
how can I get device orientation to rotate pictures.

I know how to rotate picture, but I couldn't get correct orientation (between 0 and 360 degree).

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

hosseintavakoli-7723 avatar image
0 Votes"
hosseintavakoli-7723 answered hosseintavakoli-7723 edited

Thank, Its done!

 void Accelerometer_ReadingChanged(object sender, AccelerometerChangedEventArgs e)
         {
             var data = e.Reading;
             int _rotation = 0;
             double X = data.Acceleration.X;
             double Y = data.Acceleration.Y;
             lblPictureTitle.Text = data.Acceleration.X.ToString() + "\n" + data.Acceleration.Y.ToString();
             lblProjectTitle.Text = data.Acceleration.Z.ToString();
             if(Y>=0)
             {
                 if (X > -0.5 && X < 0.5)
                     _rotation = 0;
                 else if (X > 0.5 && X < 1.2)
                     _rotation = 90;
                 else if (X > -1.2 && X < -0.5)
                     _rotation = -90;
             }
             else
             {
                 if (X > -1.2 && X < -0.5)
                     _rotation = -90;
                 else if (X > -0.5 && X < 0.5)
                     _rotation = 180;
                 else if (X > 0.5 && X < 1.2)
                     _rotation = 90;
             }
    
             if(ScreenRotation!=_rotation)
             {
                 ScreenRotation = _rotation;
                 RotateElements(_rotation);
             }
         }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

LeonLu-MSFT avatar image
0 Votes"
LeonLu-MSFT answered LeonLu-MSFT edited

Hello,​

Welcome to our Microsoft Q&A platform!

You can use Xamarin.Essentials: Device Display Information to get the current orientation degree.

private void Button_Clicked(object sender, EventArgs e)
        {
            var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;

            // Orientation (Landscape, Portrait, Square, Unknown)
            var orientation = mainDisplayInfo.Orientation;

            // Rotation (0, 90, 180, 270)
            var rotation = mainDisplayInfo.Rotation;

            DisplayAlert("Degree", rotation.ToString(), "OK");
        }


I find you use Camera2forms this demo, please do not forget to delete ScreenOrientation = ScreenOrientation.Portrait above the MainActivity.cs, then you can rotate.

106484-image.png

And if you want to get the current orientation degree. in the xamarin android or custom renderer, you can use following code as well.

IWindowManager windowManager = Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
                var rotation = windowManager.DefaultDisplay.Rotation;


======================Update=========================

using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
using Android.Content;
using Android.Hardware;
using Android.Views;

namespace App106.Droid
{
    [Activity(Label = "App106", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ScreenOrientation = ScreenOrientation.Portrait, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ISensorEventListener
    {

        private SensorManager mSensorManager;
        private Sensor mSensorGr;

        private float[] mAccelerometerReading = new float[3];

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            //var windowManager = ApplicationContext.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
            //var orientation = windowManager.DefaultDisplay.Rotation;
           
               mSensorManager = GetSystemService(Context.SensorService) as SensorManager;


               mSensorGr = mSensorManager.GetDefaultSensor(SensorType.Accelerometer);
            RegisterOrientationListener();

            LoadApplication(new App());
        }


        public void OnAccuracyChanged(Sensor sensor, SensorStatus sensorStatus)
        {

        }

        public void OnSensorChanged(SensorEvent sensorEvent)
        {
            if (sensorEvent.Sensor.Type == SensorType.Gravity)
            {
                sensorEvent.Values.CopyTo(mAccelerometerReading, 0);

                //System.Diagnostics.Debug.WriteLine($"X: {mAccelerometerReading[0]}");
                //System.Diagnostics.Debug.WriteLine($"Y: {mAccelerometerReading[1]}");
                //System.Diagnostics.Debug.WriteLine($"Z: {mAccelerometerReading[2]}");

                if (Math.Abs(mAccelerometerReading[0]) > Math.Abs(mAccelerometerReading[1]))
                {
                    App.Orientation = (mAccelerometerReading[0] > 0) ? 1 : 2;
                }
                else
                {
                    App.Orientation = 0;
                    //Reverse portrait will not be used (mAccelerometerReading[1] > 0) ? Models.Orientation.Portrait : Models.Orientation.ReversePortrait;
                }
            }

            //System.Diagnostics.Debug.WriteLine(App.Orientation.ToString());
        }

        public void RegisterOrientationListener()
        {
            mSensorManager.RegisterListener(this, mSensorGr, SensorDelay.Game);
        }

        public void UnRegisterOrientationListener()
        {
            mSensorManager.UnregisterListener(this, mSensorGr);
        }

        protected override void OnResume()
        {
            base.OnResume();

           // RegisterOrientationListener();
        }

        protected override void OnPause()
        {
            base.OnPause();

            UnRegisterOrientationListener();
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }



   
}


Best Regards,

Leon Lu



If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.



image.png (38.0 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks a lot Mr. Leon,
I want my app work only on Portrait mode, so I cant delete ScreenOrientation = ScreenOrientation.Portrait.

Is there any way to get screen orientation degree in portrait mode?

0 Votes 0 ·

We can subscibe to the gravity sensor to get it like my updated answer.

0 Votes 0 ·