Как вывести видео в Framelayout в портретный режим в Android? - PullRequest
1 голос
/ 29 мая 2020

При запуске приложения мне нужно открыть заднюю камеру и вывести видео. Для этого я использую FrameLayout. Я могу открыть камеру и показать видео. Но видео отображается в ландшафтном режиме, хотя я установил ориентацию экрана как портретную. Ниже приведен код.

MainActivity. java:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int VIDEO_CAPTURE = 1;
    private static final int MY_CAMERA_REQUEST_CODE = 100;
    private Camera mCamera;
    private CameraPreview mPreview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MainActivity.this.setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // NOT WORKING ------------------------------
        setContentView(R.layout.activity_main);

        TextView wifiTextView = (TextView) findViewById(R.id.wifi_text);

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int rssi = wifiManager.getConnectionInfo().getRssi();
        wifiTextView.setTextColor(Color.WHITE);
        wifiTextView.setText(Integer.toString(rssi));

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "No camera permission");
                requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
            }
            else {
                Log.d(TAG, "camera permission");
                mCamera = getCameraInstance();
                mPreview = new CameraPreview(this, mCamera);
                FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
                preview.addView(mPreview);
            }
        }
        else {
            Log.d(TAG, "Use camera in OnCreate");
            mCamera = getCameraInstance();
            mPreview = new CameraPreview(this, mCamera);
            FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(mPreview);
        }
    }

    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // NOT COMING HERE -------------------------------------------------------
        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Log.d(TAG, "COnfiguration LANDSCAPE");
        }
        else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.d(TAG, "COnfiguration PORTRAIT");
        }
        else {
            Log.d(TAG, "Default code");
        }
    }
}

CameraPreview. java:

/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "CameraPreview";
    private SurfaceHolder mHolder;
    private Camera mCamera;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);

        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }
}

Манифест:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:screenOrientation="portrait"
            android:configChanges="keyboardHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Макет:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:screenOrientation="portrait"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/wifi_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Я установил ориентацию экрана для основной активности как ПОРТРЕТ в манифесте и экране Ориентация FrameLayout как ПОРТРЕТА в Layout. Неподвижное видео отображается в ландшафтном режиме. Может ли кто-нибудь сообщить мне, как программно отображать видео в портретном режиме.

1 Ответ

1 голос
/ 29 мая 2020

Добавьте mCamera.setDisplayOrientation(90); в метод конструктора CameraPreview(Context context, Camera camera) и попробуйте.

setDisplayOrientation(int) метод устанавливает значение по часовой стрелке, и допустимые значения: 0, 90, 180 и 270.

Чтобы установить ориентацию для вывода видео, добавьте mediaRecorder.setOrientationHint(90); после создания экземпляра MediaRecorder, как показано ниже

 mediaRecorder = new MediaRecorder();
 mediaRecorder.setOrientationHint(90);

setOrientationHint () установит угол поворота для вывода (записано ) видео.

Для получения дополнительной информации см. ссылки ниже

1.setDisplayOrientation (int)

https://developer.android.com/reference/android/hardware/Camera#setDisplayOrientation (int ) введите здесь описание ссылки

2.setOrientationHint (int)

https://developer.android.com/reference/android/media/MediaRecorder#setOrientationHint (int)

...