'set camera Preview Aspect ratio manually with current display metrics

I tried to develop camera preview UI with selected specific aspect ratios. But I couldn't get the correct resolution based on the selected ratio. I have 9:16(full screen), 16:9, 2.35:1 and 1:1 ratio options portrait mode. My XML like below:

<FrameLayout ..>
<RelativeLayout
android:id="@+id/cameraContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?actionBarSize">
  <LinearLayout 
   android:id="@+id/cameraPreview"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_centerVertical="true"/>
</RelativeLayout>
</FrameLayout> 

I tried to change cameraContainer width and height change and then I expect to same changing to camera. But It could not happen. My kotlin code is below:

fun setRatio(selectedRatioId:Int){

when(selectedRatioId){
   1->{
     //9:16
    cameraContainerParams.height = gettingDisplayMetrics.height
   }
   2->{
   //16:9
    cameraContainerParams.height = (gettingDisplayMetrics.width*9) /16
   }
   3->{
   //1:1
    cameraContainerParams.height = gettingDisplayMetrics.width
   }
    3->{
   //2.35:1
    cameraContainerParams.height = ((gettingDisplayMetrics.width) / 2.35).toInt()
   } 

}
    cameraContainerParams.width = gettingDisplayMetrics.width
    cameraContainer.layoutParams = cameraContainerParams

}

result is(p40 lite): 9:16 is output 1080x2090 but camera output 992x 1920 16:9 is output 1080x 607 (expected 1080 x 608) 1:1 is output 480 x 480 (I expect 1080 x 1080) 2.35:1 is output 1080 x 459( expected 1080 x 460)

how can I set the correct aspect value camera with the selection?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source