Xamarin forms get device sensor rotation (orientation)

hossein tavakoli 471 Reputation points
2021-06-16T20:12:29.54+00:00

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).

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,337 questions
0 comments No comments
{count} votes

Accepted answer
  1. hossein tavakoli 471 Reputation points
    2021-06-18T21:15:08.483+00:00

    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);
                }
            }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 74,641 Reputation points Microsoft Vendor
    2021-06-17T07:14:59.57+00:00

    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.