banner



How To Add A Viewfinder To A Camera

When adding a preview to your app, use PreviewView, which is a View that tin be cropped, scaled, and rotated for proper display.

The epitome preview streams to a surface inside the PreviewView when the camera becomes active.

Employ the PreviewView

Implementing a preview for CameraX using PreviewView involves the following steps, which are covered in afterwards sections:

  1. Optionally configure a CameraXConfig.Provider.
  2. Add together a PreviewView to your layout.
  3. Request a ProcessCameraProvider.
  4. On View creation, check for the ProcessCameraProvider.
  5. Select a camera and bind the lifecycle and use cases.

Using PreviewView has some limitations. When using PreviewView, you can't practise whatever of the post-obit things:

  • Create a SurfaceTexture to set on TextureView and Preview.SurfaceProvider.
  • Recall the SurfaceTexture from TextureView and set it on Preview.SurfaceProvider.
  • Get the Surface from SurfaceView and set it on Preview.SurfaceProvider.

If any of these happen, then the Preview will stop streaming frames to the PreviewView.

Add a PreviewView to your layout

The following sample shows a PreviewView in a layout:

<FrameLayout     android:id="@+id/container">         <androidx.photographic camera.view.PreviewView             android:id="@+id/previewView" /> </FrameLayout>          

Request a CameraProvider

The following code shows how to asking a CameraProvider:

Kotlin

import androidx.camera.lifecycle.ProcessCameraProvider import com.google.common.util.concurrent.ListenableFuture  class MainActivity : AppCompatActivity() {     private lateinit var cameraProviderFuture : ListenableFuture<ProcessCameraProvider>     override fun onCreate(savedInstanceState: Package?) {         cameraProviderFuture = ProcessCameraProvider.getInstance(this)     } }            

Coffee

import androidx.photographic camera.lifecycle.ProcessCameraProvider import com.google.mutual.util.concurrent.ListenableFuture  public grade MainActivity extends AppCompatActivity {     private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;      @Override     protected void onCreate(@Nullable Bundle savedInstanceState) {         cameraProviderFuture = ProcessCameraProvider.getInstance(this);     } }            

Check for CameraProvider availability

After requesting a CameraProvider, verify that its initialization succeeded when the view is created. The following code shows how to practise this:

Kotlin

cameraProviderFuture.addListener(Runnable {     val cameraProvider = cameraProviderFuture.get()     bindPreview(cameraProvider) }, ContextCompat.getMainExecutor(this))            

Java

cameraProviderFuture.addListener(() -> {     endeavour {         ProcessCameraProvider cameraProvider = cameraProviderFuture.become();         bindPreview(cameraProvider);     } grab (ExecutionException | InterruptedException due east) {         // No errors need to be handled for this Time to come.         // This should never be reached.     } }, ContextCompat.getMainExecutor(this));            

For an example of the bindPreview function used in this sample, see the lawmaking provided in the next section.

Select a photographic camera and bind the lifecycle and use cases

Once y'all have created and confirmed the CameraProvider, do the post-obit:

  1. Create a Preview.
  2. Specify the desired photographic camera LensFacing pick.
  3. Bind the selected camera and any use cases to the lifecycle.
  4. Connect the Preview to the PreviewView.

The post-obit code shows an example:

Kotlin

fun bindPreview(cameraProvider : ProcessCameraProvider) {     var preview : Preview = Preview.Builder()             .build()      var cameraSelector : CameraSelector = CameraSelector.Architect()           .requireLensFacing(CameraSelector.LENS_FACING_BACK)           .build()      preview.setSurfaceProvider(previewView.getSurfaceProvider())      var photographic camera = cameraProvider.bindToLifecycle(this as LifecycleOwner, cameraSelector, preview) }            

Java

void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {     Preview preview = new Preview.Builder()             .build();      CameraSelector cameraSelector = new CameraSelector.Builder()             .requireLensFacing(CameraSelector.LENS_FACING_BACK)             .build();      preview.setSurfaceProvider(previewView.getSurfaceProvider());      Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector, preview); }            

Note that bindToLifecycle() returns a Photographic camera object. See this guide for more information well-nigh decision-making camera output, such as zoom and exposure.

You are now done implementing the camera preview. Build your app and confirm that your preview appears in your app and functions as you intend it to.

Boosted controls for PreviewView

CameraX PreviewView provides some additional APIs to configure properties such equally:

  • The implementation mode for rendering preview streams
  • The preview paradigm calibration blazon

Implementation mode

PreviewView can employ one of the post-obit modes to render a preview stream onto the target View:

  • Performance is the default mode. PreviewView uses a SurfaceView to display the video stream, merely will fall dorsum to a TextureView in certain cases. SurfaceView has a dedicated drawing surface, which has a ameliorate chance of beingness implemented with a hardware overlay by the internal hardware compositor, especially when in that location are no other UI elements (like buttons) on top of the preview video. By rendering with a hardware overlay, video frames avert a GPU path, which tin reduce platform power consumption and latency.

  • Uniform manner. In this manner, PreviewView uses a TextureView which, unlike SurfaceView, does not have a defended cartoon surface. Equally a upshot, video is rendered with blending so that information technology can be displayed. During this extra footstep, the application can perform additional processing, such as scaling and rotating videos without brake.

Use PreviewView.setImplementationMode() to select the implementation mode suitable for your application. If the default Functioning fashion isn't suitable for your application, the post-obit code sample shows how to set Compatible style:

Kotlin

// viewFinder is a PreviewView example viewFinder.implementationMode = PreviewView.ImplementationMode.COMPATIBLE          

Scale type

When the preview video resolution differs from the dimensions of your target PreviewView, video content needs to be fit to the view either by cropping or letterboxing (maintaining the original aspect ratio). PreviewView provides the post-obit ScaleTypes for this purpose:

  • FIT_CENTER, FIT_START, and FIT_END for letterboxing. The full video content is scaled (either up or downwards) to the maximum possible size that tin be displayed in the target PreviewView. Notwithstanding, while the full video frame is visible, some portion of the screen may be bare. Depending on which of these three calibration types you choose, the video frame will be aligned to the center, beginning, or cease of the target View.

  • FILL_CENTER, FILL_START, FILL_END for cropping. If a video doesn't friction match the PreviewView aspect ratio, only a portion of the content is visible, but the video fills the entire PreviewView.

The default calibration type CameraX uses is FILL_CENTER. Use PreviewView.setScaleType() to set the scale type most advisable for your awarding. The following code sample sets the FIT_CENTER scale type:

Kotlin

// viewFinder is a PreviewView example viewFinder.scaleType = PreviewView.ScaleType.FIT_CENTER          

The process for displaying a video consists of the following steps:

  1. Scale the video:
    • For FIT_* calibration types, scale the video with min(dst.width/src.width, dst.height/src.height).
    • For FILL_* calibration types, scale the video with max(dst.width/src.width, dst.height/src.height).
  2. Align the scaled video with the destination PreviewView:
    • For FIT_CENTER/FILL_CENTER, center marshal the scaled video and the destination PreviewView.
    • For FIT_START/FILL_START, marshal the scaled video and the destination PreviewView with respect to the top-left corner of each.
    • For FIT_END/FILL_END, align the scaled video and the destination PreviewView with respect to the lesser-right corner of each.

For case, here is a 640x480 source video and a 1920x1080 destination PreviewView:

Image showing a 640x480 video compared to a 1920x1080 preview

The following prototype shows the FIT_START / FIT_CENTER / FIT_END scaling procedure:

Image showing the FIT_START, FIT_CENTER, and FIT_END scaling process

The procedure works like this:

  1. Calibration the video frame (maintaining the original aspect ratio) with min(1920/640, 1080/400) = 2.25 to get an intermediate video frame of 1440x1080.
  2. Align the 1440x1080 video frame with the 1920x1080 PreviewView.
    • For FIT_CENTER, align the video frame with the eye of the PreviewView window. The starting and ending 240 pixel columns of the PreviewView are blank.
    • For FIT_START, align the video frame with the start (top-left corner) of the PreviewView window. The ending 480 pixel columns of the PreviewView are blank.
    • For FIT_END, marshal the video frame with the end (bottom-right corner) of the PreviewView window. The starting 480 pixel columns of the PreviewView are blank.

The following prototype shows the FILL_START / FILL_CENTER / FILL_END scaling process:

Image showing the FILL_START, FILL_CENTER, and FILL_END scaling process

The process works similar this:

  1. Scale the video frame with max(1920/640, 1080/400) = 3 to become an intermediate video frame of 1920x1440 (which is larger than the size of the PreviewView).
  2. Ingather the 1920x1440 video frame to fit the 1920x1080 PreviewView window.
    • For FILL_CENTER, crop 1920x1080 from the centre of the 1920x1440 scaled video. The superlative and bottom 180 lines of video are not visible.
    • For FILL_START, crop 1920x1080 from the first of the 1920x1440 scaled video. The bottom 360 lines of video are non visible.
    • For FILL_END, crop 1920x1080 from the end of the 1920x1440 scaled video. The top 360 lines of video are not visible.

Additional resources

To learn more than most CameraX, encounter the following additional resource.

Codelab

  • Getting Started with CameraX
  • Code sample

  • Official CameraX sample app
  • Source: https://developer.android.com/training/camerax/preview

    Posted by: dixonsatereat.blogspot.com

    0 Response to "How To Add A Viewfinder To A Camera"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel