If you use SurfaceView to display the output of the cameraโs preview, and you want your preview to not be distorted, both in the preview mode and in the landscape, you need to make sure that the aspect ratio of your SurfaceView matches the aspect ratio of the cameraโs preview size. SurfaceView simply scales the preview to fit inside itself, so if it is 500x500 and the preview size is 640x480, the preview will look stretched vertically.
Conceptually, the easiest approach is to simply manually set the width and height of the SurfaceView by updating the SurfaceView layout to a fixed size using LayoutParams and setLayoutParams . The problem with this approach is that it can be fragile with different screen sizes, since you need to figure out what pixel sizes you really want, and for a simple layout on different Android devices, you really want to think in dp instead of pixels. But for testing, you can simply force SurfaceView to have the screen width of the test device and the height set to
surface height = preview height / preview width * surface width
The best approach would be to create a new class inherited from SurfaceView that performs the necessary aspect ratio adjustments in the onMeasure method. Explaining this in detail, you can read in detail the documentation for custom components on the Android developer site. But, roughly speaking, you need to set the width / height values, which always lead to the same aspect ratio as the size of the camera preview that you configured.
Once you get the right image in the right size, you usually also need to rotate the camera preview output using setDisplayOrientation ; Generating orientation maths can be confusing, so use the sample code provided in the documentation link above to figure it out.
Basically, there is one coordinate system in the world, the camera sensor has another (fixed on the device), and the user interface system has a third (fixed in relation to your current orientation), and all three can change relative to each other. Although the correct orientation of the preview does not depend on the position of the device relative to the world, the orientation of the pictures taken by the camera (which is setRotation ).
source share