google / cameraview

[DEPRECATED] Easily integrate Camera features into your Android app
Apache License 2.0
4.74k stars 1.03k forks source link

NPE while setting the aspect ratio #272

Open doruchidean-lifeishard opened 5 years ago

doruchidean-lifeishard commented 5 years ago

I'm trying to set the aspect ratio for the preview like so:

       @Override
        public void onCameraOpened(CameraView cameraView) {
            super.onCameraOpened(cameraView);
            for (AspectRatio ar : cameraView.getSupportedAspectRatios()) {
                if (ar.getX() == 3 && ar.getY() == 2) {
                    cameraView.setAspectRatio(ar);  //NPE exception
                    break;
                }
            }
        }

and I get a NPE exception: Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.SortedSet.last()' on a null object reference at com.google.android.cameraview.Camera1.adjustCameraParameters(Camera1.java:333) at com.google.android.cameraview.Camera1.setAspectRatio(Camera1.java:174) at com.google.android.cameraview.CameraView.setAspectRatio(CameraView.java:346)

What I'm trying to accomplish is to have the same aspectRatio for the preview and the resulted bitmap (so I can crop the photo on a specific location) Is there another way to accomplish this?

William353 commented 5 years ago
        final Set<AspectRatio> ratioSet = mCameraView.getSupportedAspectRatios();
        if (ratioSet != null && !ratioSet.isEmpty()) {
            AspectRatio[] ratioArray = ratioSet.toArray(new AspectRatio[ratioSet.size()]);
            if (ratioArray != null && ratioArray.length != 0) {
                Arrays.sort(ratioArray);
                for (int i = ratioArray.length - 1; i >= 0; i--) {
                    AspectRatio aspectRatio = ratioArray[i];
                    try {
                        mCameraView.setAspectRatio(aspectRatio);
                        break;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

Some devices can not apply the same aspectRatio , I tried this, it work for me