Package 

Class CameraView

  • All Implemented Interfaces:
    android.graphics.drawable.Drawable.Callback , android.view.KeyEvent.Callback , android.view.ViewManager , android.view.ViewParent , android.view.accessibility.AccessibilityEventSource , androidx.lifecycle.LifecycleObserver

    
    public class CameraView
    extends FrameLayout implements LifecycleObserver
                        

    Entry point for the whole library. Please read documentation for usage and full set of features.

    • Method Summary

      Modifier and Type Method Description
      boolean mapGesture(@NonNull() Gesture gesture, @NonNull() GestureAction action) Maps a Gesture to a certain gesture action.
      void clearGesture(@NonNull() Gesture gesture) Clears any action mapped to the given gesture.
      GestureAction getGestureAction(@NonNull() Gesture gesture) Returns the action currently mapped to the given gesture.
      boolean onInterceptTouchEvent(MotionEvent ev)
      boolean onTouchEvent(MotionEvent event)
      void setRequestPermissions(boolean requestPermissions) Sets permissions flag if you want enable auto check permissions or disable it.
      boolean isOpened() Returns whether the camera engine has started.
      void setLifecycleOwner(@Nullable() LifecycleOwner owner) Sets the lifecycle owner for this view.
      void open() Starts the camera preview, if not started already.This should be called onResume(), or when you are ready with permissions.
      void close() Stops the current preview, if any was started.This should be called onPause().
      void destroy() Destroys this instance, releasing immediatelythe camera resource.
      void setExperimental(boolean experimental) Sets the experimental flag which occasionally can enablenew, unstable beta features.
      void set(@NonNull() Control control) Shorthand for the appropriate set* method.
      <T extends Control> T get(@NonNull() Class<T> controlClass) Shorthand for the appropriate get* method.
      void setPreview(@NonNull() Preview preview) Controls the preview engine.
      Preview getPreview() Returns the current preview control.
      void setEngine(@NonNull() Engine engine) Controls the core engine.
      Engine getEngine() Returns the current engine control.
      CameraOptions getCameraOptions() Returns a CameraOptions instance holding supported options for this camerasession.
      void setExposureCorrection(float EVvalue) Sets exposure adjustment, in EV stops.
      float getExposureCorrection() Returns the current exposure correction value, typically 0at start-up.
      void setZoom(float zoom) Sets a zoom value.
      float getZoom() Returns the current zoom value, something between 0 and 1.
      void setGrid(@NonNull() Grid gridMode) Controls the grids to be drawn over the current layout.
      Grid getGrid() Gets the current grid mode.
      void setGridColor(@ColorInt() int color) Controls the color of the grid lines that will be drawnover the current layout.
      int getGridColor() Returns the current grid color.
      void setHdr(@NonNull() Hdr hdr) Controls the grids to be drawn over the current layout.
      Hdr getHdr() Gets the current hdr value.
      void setLocation(double latitude, double longitude) Set location coordinates to be found later in the EXIF header
      void setLocation(@Nullable() Location location) Set location values to be found later in the EXIF header
      Location getLocation() Retrieves the location previously applied with setLocation().
      void setWhiteBalance(@NonNull() WhiteBalance whiteBalance) Sets desired white balance to current camera session.
      WhiteBalance getWhiteBalance() Returns the current white balance behavior.
      void setFacing(@NonNull() Facing facing) Sets which camera sensor should be used.
      Facing getFacing() Gets the facing camera currently being used.
      Facing toggleFacing() Toggles the facing value between BACK and FRONT.
      void setFlash(@NonNull() Flash flash) Sets the flash mode.
      Flash getFlash() Gets the current flash mode.
      void setAudio(@NonNull() Audio audio) Controls the audio mode.
      Audio getAudio() Gets the current audio value.
      void setAutoFocusMarker(@Nullable() AutoFocusMarker autoFocusMarker) Sets an AutoFocusMarker to be notified of metering start, end and fail eventsso that it can draw elements on screen.
      void setAutoFocusResetDelay(long delayMillis) Sets the current delay in milliseconds to reset the focus after a metering event.
      long getAutoFocusResetDelay() Returns the current delay in milliseconds to reset the focus after a metering event.
      void startAutoFocus(float x, float y) Starts a 3A touch metering process at the given coordinates, with respectto the view width and height.
      void startAutoFocus(@NonNull() RectF region) Starts a 3A touch metering process at the given coordinates, with respectto the view width and height.
      void setPreviewStreamSize(@NonNull() SizeSelector selector) ADVANCED FEATURE - sets a size selector for the preview stream.
      void setMode(@NonNull() Mode mode) Set the current session type to either picture or video.
      Mode getMode() Gets the current mode.
      void setPictureSize(@NonNull() SizeSelector selector) Sets a capture size selector for picture mode.
      void setPictureMetering(boolean enable) Whether the engine should perform a metering sequence before taking pictures requestedwith takePicture.
      boolean getPictureMetering() Whether the engine should perform a metering sequence before taking pictures requestedwith takePicture.
      void setPictureSnapshotMetering(boolean enable) Whether the engine should perform a metering sequence before taking pictures requestedwith takePictureSnapshot.
      boolean getPictureSnapshotMetering() Whether the engine should perform a metering sequence before taking pictures requestedwith takePictureSnapshot.
      void setPictureFormat(@NonNull() PictureFormat pictureFormat) Sets the format for pictures taken with takePicture.
      PictureFormat getPictureFormat() Returns the current picture format.
      void setVideoSize(@NonNull() SizeSelector selector) Sets a capture size selector for video mode.
      void setVideoBitRate(int bitRate) Sets the bit rate in bits per second for video capturing.
      int getVideoBitRate() Returns the current video bit rate.
      void setPreviewFrameRateExact(boolean videoFrameRateExact) A flag to control the behavior when calling setPreviewFrameRate.
      boolean getPreviewFrameRateExact() Returns whether we want to set preview fps as exact as we set through setPreviewFrameRate.
      void setPreviewFrameRate(float frameRate) Sets the preview frame rate in frames per second.
      float getPreviewFrameRate() Returns the current preview frame rate.This can return 0F if no frame rate was set.
      void setAudioBitRate(int bitRate) Sets the bit rate in bits per second for audio capturing.
      int getAudioBitRate() Returns the current audio bit rate.
      void setAudioCodec(@NonNull() AudioCodec codec) Sets the encoder for audio recordings.
      AudioCodec getAudioCodec() Gets the current encoder for audio recordings.
      void addCameraListener(@NonNull() CameraListener cameraListener) Adds a CameraListener instance to be notified of allinteresting events that happen during the camera lifecycle.
      void removeCameraListener(@NonNull() CameraListener cameraListener) Remove a CameraListener that was previously registered.
      void clearCameraListeners() Clears the list of CameraListener that are registeredto camera events.
      void takePicture() Asks the camera to capture an image of the current scene.
      void takePictureSnapshot() Asks the camera to capture a snapshot of the current preview.
      void takeVideo(@NonNull() File file) Starts recording a video.
      void takeVideo(@NonNull() FileDescriptor fileDescriptor) Starts recording a video.
      void takeVideoSnapshot(@NonNull() File file) Starts recording a fast, low quality video snapshot.
      void takeVideo(@NonNull() File file, int durationMillis) Starts recording a video.
      void takeVideo(@NonNull() FileDescriptor fileDescriptor, int durationMillis) Starts recording a video.
      void takeVideoSnapshot(@NonNull() File file, int durationMillis) Starts recording a fast, low quality video snapshot.
      void stopVideo() Stops capturing video or video snapshots being recorded, if there was any.
      void setSnapshotMaxWidth(int maxWidth) Sets the max width for snapshots taken with takePictureSnapshot or takeVideoSnapshot.
      void setSnapshotMaxHeight(int maxHeight) Sets the max height for snapshots taken with takePictureSnapshot or takeVideoSnapshot.
      int getSnapshotMaxWidth() The max width for snapshots.
      int getSnapshotMaxHeight() The max height for snapshots.
      Size getSnapshotSize() Returns the size used for snapshots, or null if it hasn't been computed(for example if the surface is not ready).
      Size getPictureSize() Returns the size used for pictures taken with takePicture,or null if it hasn't been computed (for example if the surface is not ready),or null if we are in video mode.The size is rotated to match the output orientation.
      Size getVideoSize() Returns the size used for videos taken with takeVideo,or null if it hasn't been computed (for example if the surface is not ready),or null if we are in picture mode.The size is rotated to match the output orientation.
      void setPlaySounds(boolean playSounds) Controls whether CameraView should play sound effects on certainevents (picture taken, focus complete).
      boolean getPlaySounds() Gets the current sound effect behavior.
      void setUseDeviceOrientation(boolean useDeviceOrientation) Controls whether picture and video output should consider the current device orientation.For example, when true, if the user rotates the device before taking a picture, the picturewill be rotated as well.
      boolean getUseDeviceOrientation() Gets the current behavior for considering the device orientation when returning pictureor video outputs.
      void setVideoCodec(@NonNull() VideoCodec codec) Sets the encoder for video recordings.
      VideoCodec getVideoCodec() Gets the current encoder for video recordings.
      void setVideoMaxSize(long videoMaxSizeInBytes) Sets the maximum size in bytes for recorded video files.Once this size is reached, the recording will automatically stop.Defaults to unlimited size.
      long getVideoMaxSize() Returns the maximum size in bytes for recorded video files, or 0if no size was set.
      void setVideoMaxDuration(int videoMaxDurationMillis) Sets the maximum duration in milliseconds for video recordings.Once this duration is reached, the recording will automatically stop.Defaults to unlimited duration.
      int getVideoMaxDuration() Returns the maximum duration in milliseconds for video recordings, or 0if no limit was set.
      boolean isTakingVideo() Returns true if the camera is currently recording a video
      boolean isTakingPicture() Returns true if the camera is currently capturing a picture
      void setDrawHardwareOverlays(boolean on) Sets the overlay layout hardware canvas capture mode to allow hardwareaccelerated views to be captured in snapshots
      boolean getDrawHardwareOverlays() Returns true if the overlay layout is set to capture the hardware canvasof child views
      void addFrameProcessor(@Nullable() FrameProcessor processor) Adds a FrameProcessor instance to be notified ofnew frames in the preview stream.
      void removeFrameProcessor(@Nullable() FrameProcessor processor) Remove a FrameProcessor that was previously registered.
      void clearFrameProcessors() Clears the list of FrameProcessor that have been registeredto preview frames.
      void setFrameProcessingMaxWidth(int maxWidth) Sets the max width for frame processing Frames.
      void setFrameProcessingMaxHeight(int maxHeight) Sets the max height for frame processing Frames.
      int getFrameProcessingMaxWidth() The max width for frame processing frames.
      int getFrameProcessingMaxHeight() The max height for frame processing frames.
      void setFrameProcessingFormat(int format) Sets the android.graphics.ImageFormat for frame processing.
      int getFrameProcessingFormat() Returns the current frame processing format.
      void setFrameProcessingPoolSize(int poolSize) Sets the frame processing pool size.
      int getFrameProcessingPoolSize() Returns the current frame processing pool size.
      void setFrameProcessingExecutors(int executors) Sets the thread pool size for frame processing.
      int getFrameProcessingExecutors() Returns the current executors count.
      FrameLayout.LayoutParams generateLayoutParams(AttributeSet attributeSet)
      void addView(View child, int index, ViewGroup.LayoutParams params)
      void removeView(View view)
      void setFilter(@NonNull() Filter filter) Applies a real-time filter to the camera preview, if it supports it.
      Filter getFilter() Returns the current real-time filter applied to the camera preview.This method will throw an exception if the current preview does not support real-timefilters.
      • Methods inherited from class android.widget.FrameLayout

        generateLayoutParams, getAccessibilityClassName, getConsiderGoneChildrenWhenMeasuring, getMeasureAllChildren, setForegroundGravity, setMeasureAllChildren, shouldDelayChildPressedState
      • Methods inherited from class android.view.ViewGroup

        addChildrenForAccessibility, addExtraDataToAccessibilityNodeInfo, addFocusables, addKeyboardNavigationClusters, addStatesFromChildren, addTouchables, addView, bringChildToFront, childDrawableStateChanged, childHasTransientStateChanged, clearChildFocus, clearDisappearingChildren, clearFocus, dispatchApplyWindowInsets, dispatchCapturedPointerEvent, dispatchConfigurationChanged, dispatchCreateViewTranslationRequest, dispatchDisplayHint, dispatchDragEvent, dispatchDrawableHotspotChanged, dispatchFinishTemporaryDetach, dispatchKeyEvent, dispatchKeyEventPreIme, dispatchKeyShortcutEvent, dispatchPointerCaptureChanged, dispatchProvideAutofillStructure, dispatchProvideStructure, dispatchScrollCaptureSearch, dispatchSetActivated, dispatchSetSelected, dispatchStartTemporaryDetach, dispatchSystemUiVisibilityChanged, dispatchTouchEvent, dispatchTrackballEvent, dispatchUnhandledMove, dispatchWindowFocusChanged, dispatchWindowInsetsAnimationEnd, dispatchWindowInsetsAnimationPrepare, dispatchWindowInsetsAnimationProgress, dispatchWindowInsetsAnimationStart, dispatchWindowSystemUiVisiblityChanged, dispatchWindowVisibilityChanged, endViewTransition, findFocus, findViewsWithText, focusSearch, focusableViewAvailable, gatherTransparentRegion, getChildAt, getChildCount, getChildMeasureSpec, getChildVisibleRect, getClipChildren, getClipToPadding, getDescendantFocusability, getFocusedChild, getLayoutAnimation, getLayoutAnimationListener, getLayoutMode, getLayoutTransition, getNestedScrollAxes, getOverlay, getPersistentDrawingCache, getTouchscreenBlocksFocus, hasFocus, hasTransientState, indexOfChild, invalidateChild, invalidateChildInParent, isAlwaysDrawnWithCacheEnabled, isAnimationCacheEnabled, isLayoutSuppressed, isMotionEventSplittingEnabled, isTransitionGroup, jumpDrawablesToCurrentState, layout, notifySubtreeAccessibilityStateChanged, offsetDescendantRectToMyCoords, offsetRectIntoDescendantCoords, onDescendantInvalidated, onInterceptHoverEvent, onInterceptTouchEvent, onNestedFling, onNestedPreFling, onNestedPrePerformAccessibilityAction, onNestedPreScroll, onNestedScroll, onNestedScrollAccepted, onRequestSendAccessibilityEvent, onResolvePointerIcon, onStartNestedScroll, onStopNestedScroll, onViewAdded, onViewRemoved, recomputeViewAttributes, removeAllViews, removeAllViewsInLayout, removeView, removeViewAt, removeViewInLayout, removeViews, removeViewsInLayout, requestChildFocus, requestChildRectangleOnScreen, requestDisallowInterceptTouchEvent, requestFocus, requestSendAccessibilityEvent, requestTransparentRegion, restoreDefaultFocus, scheduleLayoutAnimation, setAddStatesFromChildren, setAlwaysDrawnWithCacheEnabled, setAnimationCacheEnabled, setClipChildren, setClipToPadding, setDescendantFocusability, setLayoutAnimation, setLayoutAnimationListener, setLayoutMode, setLayoutTransition, setMotionEventSplittingEnabled, setOnHierarchyChangeListener, setPersistentDrawingCache, setTouchscreenBlocksFocus, setTransitionGroup, setWindowInsetsAnimationCallback, showContextMenuForChild, startActionModeForChild, startLayoutAnimation, startViewTransition, suppressLayout, updateViewLayout
      • Methods inherited from class android.view.View

        addOnAttachStateChangeListener, addOnLayoutChangeListener, addOnUnhandledKeyEventListener, animate, announceForAccessibility, autofill, bringToFront, buildDrawingCache, buildLayer, callOnClick, canResolveLayoutDirection, canResolveTextAlignment, canResolveTextDirection, canScrollHorizontally, canScrollVertically, cancelDragAndDrop, cancelLongPress, cancelPendingInputEvents, checkInputConnectionProxy, clearAnimation, clearViewTranslationCallback, combineMeasuredStates, computeScroll, computeSystemWindowInsets, createAccessibilityNodeInfo, createContextMenu, destroyDrawingCache, dispatchGenericMotionEvent, dispatchNestedFling, dispatchNestedPreFling, dispatchNestedPrePerformAccessibilityAction, dispatchNestedPreScroll, dispatchNestedScroll, dispatchPopulateAccessibilityEvent, draw, drawableHotspotChanged, findViewById, findViewWithTag, forceHasOverlappingRendering, forceLayout, generateDisplayHash, generateViewId, getAccessibilityDelegate, getAccessibilityLiveRegion, getAccessibilityNodeProvider, getAccessibilityPaneTitle, getAccessibilityTraversalAfter, getAccessibilityTraversalBefore, getAlpha, getAnimation, getAnimationMatrix, getApplicationWindowToken, getAttributeResolutionStack, getAttributeSourceResourceMap, getAutofillHints, getAutofillId, getAutofillType, getAutofillValue, getBackground, getBackgroundTintBlendMode, getBackgroundTintList, getBackgroundTintMode, getBaseline, getBottom, getCameraDistance, getClipBounds, getClipBounds, getClipToOutline, getContentCaptureSession, getContentDescription, getContext, getDefaultFocusHighlightEnabled, getDefaultSize, getDisplay, getDrawableState, getDrawingCache, getDrawingCacheBackgroundColor, getDrawingCacheQuality, getDrawingRect, getDrawingTime, getElevation, getExplicitStyle, getFilterTouchesWhenObscured, getFitsSystemWindows, getFocusable, getFocusables, getFocusedRect, getForeground, getForegroundGravity, getForegroundTintBlendMode, getForegroundTintList, getForegroundTintMode, getGlobalVisibleRect, getHandler, getHasOverlappingRendering, getHeight, getHitRect, getHorizontalFadingEdgeLength, getHorizontalScrollbarThumbDrawable, getHorizontalScrollbarTrackDrawable, getId, getImportantForAccessibility, getImportantForAutofill, getImportantForContentCapture, getKeepScreenOn, getKeyDispatcherState, getLabelFor, getLayerType, getLayoutDirection, getLayoutParams, getLeft, getLocalVisibleRect, getLocationInSurface, getLocationInWindow, getLocationOnScreen, getMatrix, getMeasuredHeight, getMeasuredHeightAndState, getMeasuredState, getMeasuredWidth, getMeasuredWidthAndState, getMinimumHeight, getMinimumWidth, getNextClusterForwardId, getNextFocusDownId, getNextFocusForwardId, getNextFocusLeftId, getNextFocusRightId, getNextFocusUpId, getOnFocusChangeListener, getOutlineAmbientShadowColor, getOutlineProvider, getOutlineSpotShadowColor, getOverScrollMode, getOverlay, getPaddingBottom, getPaddingEnd, getPaddingLeft, getPaddingRight, getPaddingStart, getPaddingTop, getParent, getParentForAccessibility, getPivotX, getPivotY, getPointerIcon, getReceiveContentMimeTypes, getResources, getRevealOnFocusHint, getRight, getRootSurfaceControl, getRootView, getRootWindowInsets, getRotation, getRotationX, getRotationY, getScaleX, getScaleY, getScrollBarDefaultDelayBeforeFade, getScrollBarFadeDuration, getScrollBarSize, getScrollBarStyle, getScrollCaptureHint, getScrollIndicators, getScrollX, getScrollY, getSolidColor, getSourceLayoutResId, getStateDescription, getStateListAnimator, getSystemGestureExclusionRects, getSystemUiVisibility, getTag, getTextAlignment, getTextDirection, getTooltipText, getTop, getTouchDelegate, getTouchables, getTransitionAlpha, getTransitionName, getTranslationX, getTranslationY, getTranslationZ, getUniqueDrawingId, getVerticalFadingEdgeLength, getVerticalScrollbarPosition, getVerticalScrollbarThumbDrawable, getVerticalScrollbarTrackDrawable, getVerticalScrollbarWidth, getViewTranslationResponse, getViewTreeObserver, getVisibility, getWidth, getWindowId, getWindowInsetsController, getWindowSystemUiVisibility, getWindowToken, getWindowVisibility, getWindowVisibleDisplayFrame, getX, getY, getZ, hasExplicitFocusable, hasFocusable, hasNestedScrollingParent, hasOnClickListeners, hasOnLongClickListeners, hasOverlappingRendering, hasPointerCapture, hasWindowFocus, inflate, invalidate, invalidateDrawable, invalidateOutline, isAccessibilityFocused, isAccessibilityHeading, isActivated, isAttachedToWindow, isClickable, isContextClickable, isDirty, isDrawingCacheEnabled, isDuplicateParentStateEnabled, isEnabled, isFocusable, isFocusableInTouchMode, isFocused, isFocusedByDefault, isForceDarkAllowed, isHapticFeedbackEnabled, isHardwareAccelerated, isHorizontalFadingEdgeEnabled, isHorizontalScrollBarEnabled, isHovered, isImportantForAccessibility, isImportantForAutofill, isImportantForContentCapture, isInEditMode, isInLayout, isInTouchMode, isKeyboardNavigationCluster, isLaidOut, isLayoutDirectionResolved, isLayoutRequested, isLongClickable, isNestedScrollingEnabled, isOpaque, isPaddingRelative, isPivotSet, isPressed, isSaveEnabled, isSaveFromParentEnabled, isScreenReaderFocusable, isScrollContainer, isScrollbarFadingEnabled, isSelected, isShowingLayoutBounds, isShown, isSoundEffectsEnabled, isTemporarilyDetached, isTextAlignmentResolved, isTextDirectionResolved, isVerticalFadingEdgeEnabled, isVerticalScrollBarEnabled, isVisibleToUserForAutofill, keyboardNavigationClusterSearch, measure, offsetLeftAndRight, offsetTopAndBottom, onApplyWindowInsets, onCancelPendingInputEvents, onCapturedPointerEvent, onCheckIsTextEditor, onCreateInputConnection, onCreateViewTranslationRequest, onCreateVirtualViewTranslationRequests, onDragEvent, onDrawForeground, onFilterTouchEventForSecurity, onFinishTemporaryDetach, onGenericMotionEvent, onHoverChanged, onHoverEvent, onInitializeAccessibilityEvent, onInitializeAccessibilityNodeInfo, onKeyDown, onKeyLongPress, onKeyMultiple, onKeyPreIme, onKeyShortcut, onKeyUp, onPointerCaptureChange, onPopulateAccessibilityEvent, onProvideAutofillStructure, onProvideAutofillVirtualStructure, onProvideContentCaptureStructure, onProvideStructure, onProvideVirtualStructure, onReceiveContent, onRtlPropertiesChanged, onScreenStateChanged, onScrollCaptureSearch, onStartTemporaryDetach, onTouchEvent, onTrackballEvent, onViewTranslationResponse, onVirtualViewTranslationResponses, onVisibilityAggregated, onWindowFocusChanged, onWindowSystemUiVisibilityChanged, performAccessibilityAction, performClick, performContextClick, performHapticFeedback, performLongClick, performReceiveContent, playSoundEffect, post, postDelayed, postInvalidate, postInvalidateDelayed, postInvalidateOnAnimation, postOnAnimation, postOnAnimationDelayed, refreshDrawableState, releasePointerCapture, removeCallbacks, removeOnAttachStateChangeListener, removeOnLayoutChangeListener, removeOnUnhandledKeyEventListener, requestApplyInsets, requestFitSystemWindows, requestFocusFromTouch, requestLayout, requestPointerCapture, requestRectangleOnScreen, requestUnbufferedDispatch, requireViewById, resetPivot, resolveSize, resolveSizeAndState, restoreHierarchyState, saveAttributeDataForStyleable, saveHierarchyState, scheduleDrawable, scrollBy, scrollTo, sendAccessibilityEvent, sendAccessibilityEventUnchecked, setAccessibilityDelegate, setAccessibilityHeading, setAccessibilityLiveRegion, setAccessibilityPaneTitle, setAccessibilityTraversalAfter, setAccessibilityTraversalBefore, setActivated, setAllowClickWhenDisabled, setAlpha, setAnimation, setAnimationMatrix, setAutofillHints, setAutofillId, setBackground, setBackgroundColor, setBackgroundDrawable, setBackgroundResource, setBackgroundTintBlendMode, setBackgroundTintList, setBackgroundTintMode, setBottom, setCameraDistance, setClickable, setClipBounds, setClipToOutline, setContentCaptureSession, setContentDescription, setContextClickable, setDefaultFocusHighlightEnabled, setDrawingCacheBackgroundColor, setDrawingCacheEnabled, setDrawingCacheQuality, setDuplicateParentStateEnabled, setElevation, setEnabled, setFadingEdgeLength, setFilterTouchesWhenObscured, setFitsSystemWindows, setFocusable, setFocusableInTouchMode, setFocusedByDefault, setForceDarkAllowed, setForeground, setForegroundTintBlendMode, setForegroundTintList, setForegroundTintMode, setHapticFeedbackEnabled, setHasTransientState, setHorizontalFadingEdgeEnabled, setHorizontalScrollBarEnabled, setHorizontalScrollbarThumbDrawable, setHorizontalScrollbarTrackDrawable, setHovered, setId, setImportantForAccessibility, setImportantForAutofill, setImportantForContentCapture, setKeepScreenOn, setKeyboardNavigationCluster, setLabelFor, setLayerPaint, setLayerType, setLayoutDirection, setLayoutParams, setLeft, setLeftTopRightBottom, setLongClickable, setMinimumHeight, setMinimumWidth, setNestedScrollingEnabled, setNextClusterForwardId, setNextFocusDownId, setNextFocusForwardId, setNextFocusLeftId, setNextFocusRightId, setNextFocusUpId, setOnApplyWindowInsetsListener, setOnCapturedPointerListener, setOnClickListener, setOnContextClickListener, setOnCreateContextMenuListener, setOnDragListener, setOnFocusChangeListener, setOnGenericMotionListener, setOnHoverListener, setOnKeyListener, setOnLongClickListener, setOnReceiveContentListener, setOnScrollChangeListener, setOnSystemUiVisibilityChangeListener, setOnTouchListener, setOutlineAmbientShadowColor, setOutlineProvider, setOutlineSpotShadowColor, setOverScrollMode, setPadding, setPaddingRelative, setPivotX, setPivotY, setPointerIcon, setPressed, setRenderEffect, setRevealOnFocusHint, setRight, setRotation, setRotationX, setRotationY, setSaveEnabled, setSaveFromParentEnabled, setScaleX, setScaleY, setScreenReaderFocusable, setScrollBarDefaultDelayBeforeFade, setScrollBarFadeDuration, setScrollBarSize, setScrollBarStyle, setScrollCaptureCallback, setScrollCaptureHint, setScrollContainer, setScrollIndicators, setScrollX, setScrollY, setScrollbarFadingEnabled, setSelected, setSoundEffectsEnabled, setStateDescription, setStateListAnimator, setSystemGestureExclusionRects, setSystemUiVisibility, setTag, setTextAlignment, setTextDirection, setTooltipText, setTop, setTouchDelegate, setTransitionAlpha, setTransitionName, setTransitionVisibility, setTranslationX, setTranslationY, setTranslationZ, setVerticalFadingEdgeEnabled, setVerticalScrollBarEnabled, setVerticalScrollbarPosition, setVerticalScrollbarThumbDrawable, setVerticalScrollbarTrackDrawable, setViewTranslationCallback, setVisibility, setWillNotCacheDrawing, setWillNotDraw, setX, setY, setZ, showContextMenu, startActionMode, startAnimation, startDrag, startDragAndDrop, startNestedScroll, stopNestedScroll, toString, transformMatrixToGlobal, transformMatrixToLocal, unscheduleDrawable, updateDragShadow, willNotCacheDrawing, willNotDraw
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • mapGesture

         boolean mapGesture(@NonNull() Gesture gesture, @NonNull() GestureAction action)

        Maps a Gesture to a certain gesture action.For example, you can assign zoom control to the pinch gesture by just calling:cameraView.mapGesture(Gesture.PINCH, GestureAction.ZOOM);Not all actions can be assigned to a certain gesture. For example, zoom control can't beassigned to the Gesture.TAP gesture. Look at Gesture to know more.This method returns false if they are not assignable.

        Parameters:
        gesture - which gesture to map
        action - which action should be assigned
      • clearGesture

         void clearGesture(@NonNull() Gesture gesture)

        Clears any action mapped to the given gesture.

        Parameters:
        gesture - which gesture to clear
      • setRequestPermissions

         void setRequestPermissions(boolean requestPermissions)

        Sets permissions flag if you want enable auto check permissions or disable it.

        Parameters:
        requestPermissions - - true: auto check permissions enabled, false: auto check permissions disabled.
      • isOpened

         boolean isOpened()

        Returns whether the camera engine has started.

      • setLifecycleOwner

         void setLifecycleOwner(@Nullable() LifecycleOwner owner)

        Sets the lifecycle owner for this view. This means you don't needto call open, close or destroy at all.If you want that lifecycle stopped controlling the state of the camera,pass null in this method.

        Parameters:
        owner - the owner activity or fragment
      • open

         void open()

        Starts the camera preview, if not started already.This should be called onResume(), or when you are ready with permissions.

      • close

         void close()

        Stops the current preview, if any was started.This should be called onPause().

      • destroy

         void destroy()

        Destroys this instance, releasing immediatelythe camera resource.

      • setExperimental

         void setExperimental(boolean experimental)

        Sets the experimental flag which occasionally can enablenew, unstable beta features.

        Parameters:
        experimental - true to enable new features
      • set

         void set(@NonNull() Control control)

        Shorthand for the appropriate set* method.For example, if control is a Grid, this calls setGrid.

        Parameters:
        control - desired value
      • get

        @NonNull() <T extends Control> T get(@NonNull() Class<T> controlClass)

        Shorthand for the appropriate get* method.For example, if control class is a Grid, this calls getGrid.

        Parameters:
        controlClass - desired value class
      • setPreview

         void setPreview(@NonNull() Preview preview)

        Controls the preview engine. Should only be calledif this CameraView was never added to any window(like if you created it programmatically).Otherwise, it has no effect.

        Parameters:
        preview - desired preview engine
      • setEngine

         void setEngine(@NonNull() Engine engine)

        Controls the core engine. Should only be calledif this CameraView is closed (open() was never called).Otherwise, it has no effect.

        Parameters:
        engine - desired engine
      • setExposureCorrection

         void setExposureCorrection(float EVvalue)

        Sets exposure adjustment, in EV stops. A positive value will mean brighter picture.If camera is not opened, this will have no effect.If isExposureCorrectionSupported is false, this will have no effect.The provided value should be between the bounds returned by CameraOptions, or it willbe capped.

        Parameters:
        EVvalue - exposure correction value.
      • getExposureCorrection

         float getExposureCorrection()

        Returns the current exposure correction value, typically 0at start-up.

      • setZoom

         void setZoom(float zoom)

        Sets a zoom value. This is not guaranteed to be supported by the current device,but you can take a look at isZoomSupported.This will have no effect if called before the camera is opened.Zoom value should be between 0 and 1, where 1 will be the maximum available zoom.If it's not, it will be capped.

        Parameters:
        zoom - value in [0,1]
      • getZoom

         float getZoom()

        Returns the current zoom value, something between 0 and 1.

      • setGrid

         void setGrid(@NonNull() Grid gridMode)

        Controls the grids to be drawn over the current layout.

        Parameters:
        gridMode - desired grid mode
      • setGridColor

         void setGridColor(@ColorInt() int color)

        Controls the color of the grid lines that will be drawnover the current layout.

        Parameters:
        color - a resolved color
      • getGridColor

         int getGridColor()

        Returns the current grid color.

      • setHdr

         void setHdr(@NonNull() Hdr hdr)

        Controls the grids to be drawn over the current layout.

        Parameters:
        hdr - desired hdr value
      • setLocation

         void setLocation(double latitude, double longitude)

        Set location coordinates to be found later in the EXIF header

        Parameters:
        latitude - current latitude
        longitude - current longitude
      • setLocation

         void setLocation(@Nullable() Location location)

        Set location values to be found later in the EXIF header

        Parameters:
        location - current location
      • setWhiteBalance

         void setWhiteBalance(@NonNull() WhiteBalance whiteBalance)

        Sets desired white balance to current camera session.

        Parameters:
        whiteBalance - desired white balance behavior.
      • setFacing

         void setFacing(@NonNull() Facing facing)

        Sets which camera sensor should be used.

        Parameters:
        facing - a facing value.
      • setFlash

         void setFlash(@NonNull() Flash flash)

        Sets the flash mode.

        Parameters:
        flash - desired flash mode.
      • setAudio

         void setAudio(@NonNull() Audio audio)

        Controls the audio mode.

        Parameters:
        audio - desired audio value
      • setAutoFocusResetDelay

         void setAutoFocusResetDelay(long delayMillis)

        Sets the current delay in milliseconds to reset the focus after a metering event.

        Parameters:
        delayMillis - desired delay (in milliseconds).
      • getAutoFocusResetDelay

         long getAutoFocusResetDelay()

        Returns the current delay in milliseconds to reset the focus after a metering event.

      • startAutoFocus

         void startAutoFocus(float x, float y)

        Starts a 3A touch metering process at the given coordinates, with respectto the view width and height.

        Parameters:
        x - should be between 0 and getWidth()
        y - should be between 0 and getHeight()
      • startAutoFocus

         void startAutoFocus(@NonNull() RectF region)

        Starts a 3A touch metering process at the given coordinates, with respectto the view width and height.

        Parameters:
        region - should be between 0 and getWidth() / getHeight()
      • setPreviewStreamSize

         void setPreviewStreamSize(@NonNull() SizeSelector selector)

        ADVANCED FEATURE - sets a size selector for the preview stream.The SizeSelector will be invoked with the list of available sizes, and the firstacceptable size will be accepted and passed to the internal engine and surface.This is typically NOT NEEDED. The default size selector is already smart enough to respectthe picture/video output aspect ratio, and be bigger than the surface so that there is noupscaling. If all you want is set an aspect ratio, use setPictureSize and setVideoSize.When stream size changes, the CameraView is remeasured so any WRAP_CONTENT dimensionis recomputed accordingly.See the SizeSelectors class for handy utilities for creating selectors.

        Parameters:
        selector - a size selector
      • setMode

         void setMode(@NonNull() Mode mode)

        Set the current session type to either picture or video.

        Parameters:
        mode - desired session type.
      • setPictureSize

         void setPictureSize(@NonNull() SizeSelector selector)

        Sets a capture size selector for picture mode.The SizeSelector will be invoked with the list of available sizes, and the firstacceptable size will be accepted and passed to the internal engine.See the SizeSelectors class for handy utilities for creating selectors.

        Parameters:
        selector - a size selector
      • setPictureMetering

         void setPictureMetering(boolean enable)

        Whether the engine should perform a metering sequence before taking pictures requestedwith takePicture. A metering sequence includes adjusting focus, exposureand white balance to ensure a good quality of the result.When this parameter is true, the quality of the picture increases, but the latencyincreases as well. Defaults to true.This is a CAMERA2 only API. On CAMERA1, picture metering is always enabled.

        Parameters:
        enable - true to enable
      • setPictureSnapshotMetering

         void setPictureSnapshotMetering(boolean enable)

        Whether the engine should perform a metering sequence before taking pictures requestedwith takePictureSnapshot. A metering sequence includes adjusting focus,exposure and white balance to ensure a good quality of the result.When this parameter is true, the quality of the picture increases, but the latencyincreases as well. To keep snapshots fast, this defaults to false.This is a CAMERA2 only API. On CAMERA1, picture snapshot metering is always disabled.

        Parameters:
        enable - true to enable
      • setPictureFormat

         void setPictureFormat(@NonNull() PictureFormat pictureFormat)

        Sets the format for pictures taken with takePicture. This format does not applyto picture snapshots taken with takePictureSnapshot.The JPEG is always supported - for other values, please checkthe getSupportedPictureFormats value.

        Parameters:
        pictureFormat - new format
      • setVideoSize

         void setVideoSize(@NonNull() SizeSelector selector)

        Sets a capture size selector for video mode.The SizeSelector will be invoked with the list of available sizes, and the firstacceptable size will be accepted and passed to the internal engine.See the SizeSelectors class for handy utilities for creating selectors.

        Parameters:
        selector - a size selector
      • getVideoBitRate

         int getVideoBitRate()

        Returns the current video bit rate.

      • setPreviewFrameRateExact

         void setPreviewFrameRateExact(boolean videoFrameRateExact)

        A flag to control the behavior when calling setPreviewFrameRate.If the value is set to true, setPreviewFrameRate will choose the previewframe range as close to the desired new frame rate as possible. Which mean it may choose anarrow range around the desired frame rate. Note: This option will give you as exact fps asyou want but the sensor will have less freedom when adapting the exposure to the environment,which may lead to dark preview.If the value is set to false, setPreviewFrameRate will choose as broad rangeas it can.

        Parameters:
        videoFrameRateExact - whether want a more exact preview frame range
      • setPreviewFrameRate

         void setPreviewFrameRate(float frameRate)

        Sets the preview frame rate in frames per second.This rate will be used, for example, by the frame processor and in videosnapshot taken through takeVideo.A value of 0F will restore the rate to a default value.

        Parameters:
        frameRate - desired frame rate
      • getPreviewFrameRate

         float getPreviewFrameRate()

        Returns the current preview frame rate.This can return 0F if no frame rate was set.

      • getAudioBitRate

         int getAudioBitRate()

        Returns the current audio bit rate.

      • setAudioCodec

         void setAudioCodec(@NonNull() AudioCodec codec)

        Sets the encoder for audio recordings.Defaults to DEVICE_DEFAULT.

        Parameters:
        codec - requested audio codec
      • takePicture

         void takePicture()

        Asks the camera to capture an image of the current scene.This will trigger onPictureTaken if a listenerwas registered.

      • takePictureSnapshot

         void takePictureSnapshot()

        Asks the camera to capture a snapshot of the current preview.This eventually triggers onPictureTaken if a listenerwas registered.The difference with takePicture is that this capture is faster, so it might bebetter on slower cameras, though the result can be generally blurry or low quality.

      • takeVideo

         void takeVideo(@NonNull() File file)

        Starts recording a video. Video will be written to the given file,so callers should ensure they have appropriate permissions to write to the file.

        Parameters:
        file - a file where the video will be saved
      • takeVideo

         void takeVideo(@NonNull() FileDescriptor fileDescriptor)

        Starts recording a video. Video will be written to the given file,so callers should ensure they have appropriate permissions to write to the file.

        Parameters:
        fileDescriptor - a file descriptor where the video will be saved
      • takeVideoSnapshot

         void takeVideoSnapshot(@NonNull() File file)

        Starts recording a fast, low quality video snapshot. Video will be written to the given file,so callers should ensure they have appropriate permissions to write to the file.Throws an exception if API level is below 18, or if the preview being used is not GL_SURFACE.

        Parameters:
        file - a file where the video will be saved
      • takeVideo

         void takeVideo(@NonNull() File file, int durationMillis)

        Starts recording a video. Video will be written to the given file,so callers should ensure they have appropriate permissions to write to the file.Recording will be automatically stopped after the given duration, overridingtemporarily any duration limit set by setVideoMaxDuration.

        Parameters:
        file - a file where the video will be saved
        durationMillis - recording max duration
      • takeVideo

         void takeVideo(@NonNull() FileDescriptor fileDescriptor, int durationMillis)

        Starts recording a video. Video will be written to the given file,so callers should ensure they have appropriate permissions to write to the file.Recording will be automatically stopped after the given duration, overridingtemporarily any duration limit set by setVideoMaxDuration.

        Parameters:
        fileDescriptor - a file descriptor where the video will be saved
        durationMillis - recording max duration
      • takeVideoSnapshot

         void takeVideoSnapshot(@NonNull() File file, int durationMillis)

        Starts recording a fast, low quality video snapshot. Video will be written to the given file,so callers should ensure they have appropriate permissions to write to the file.Recording will be automatically stopped after the given duration, overridingtemporarily any duration limit set by setVideoMaxDuration.Throws an exception if API level is below 18, or if the preview being used is not GL_SURFACE.

        Parameters:
        file - a file where the video will be saved
        durationMillis - recording max duration
      • stopVideo

         void stopVideo()

        Stops capturing video or video snapshots being recorded, if there was any.This will fire onVideoTaken.

      • setSnapshotMaxWidth

         void setSnapshotMaxWidth(int maxWidth)

        Sets the max width for snapshots taken with takePictureSnapshot or takeVideoSnapshot. If the snapshot width exceeds this value, the snapshotwill be scaled down to match this constraint.

        Parameters:
        maxWidth - max width for snapshots
      • setSnapshotMaxHeight

         void setSnapshotMaxHeight(int maxHeight)

        Sets the max height for snapshots taken with takePictureSnapshot or takeVideoSnapshot. If the snapshot height exceeds this value, the snapshotwill be scaled down to match this constraint.

        Parameters:
        maxHeight - max height for snapshots
      • getSnapshotSize

        @Nullable() Size getSnapshotSize()

        Returns the size used for snapshots, or null if it hasn't been computed(for example if the surface is not ready). This is the preview size, rotated to matchthe output orientation, and cropped to the visible part.This also includes the setSnapshotMaxWidth and setSnapshotMaxHeight constraints.This does NOT include any constraints specific to video encoding, which aredevice specific and depend on the capabilities of the device codec.

      • getPictureSize

        @Nullable() Size getPictureSize()

        Returns the size used for pictures taken with takePicture,or null if it hasn't been computed (for example if the surface is not ready),or null if we are in video mode.The size is rotated to match the output orientation.

      • getVideoSize

        @Nullable() Size getVideoSize()

        Returns the size used for videos taken with takeVideo,or null if it hasn't been computed (for example if the surface is not ready),or null if we are in picture mode.The size is rotated to match the output orientation.

      • setPlaySounds

         void setPlaySounds(boolean playSounds)

        Controls whether CameraView should play sound effects on certainevents (picture taken, focus complete). Note that:- On API level {@literal <} 16, this flag is always false- Camera1 will always play the shutter sound when taking pictures

        Parameters:
        playSounds - whether to play sound effects
      • getPlaySounds

         boolean getPlaySounds()

        Gets the current sound effect behavior.

      • setUseDeviceOrientation

         void setUseDeviceOrientation(boolean useDeviceOrientation)

        Controls whether picture and video output should consider the current device orientation.For example, when true, if the user rotates the device before taking a picture, the picturewill be rotated as well.

        Parameters:
        useDeviceOrientation - true to consider device orientation for outputs
      • getUseDeviceOrientation

         boolean getUseDeviceOrientation()

        Gets the current behavior for considering the device orientation when returning pictureor video outputs.

      • setVideoCodec

         void setVideoCodec(@NonNull() VideoCodec codec)

        Sets the encoder for video recordings.Defaults to DEVICE_DEFAULT.

        Parameters:
        codec - requested video codec
      • setVideoMaxSize

         void setVideoMaxSize(long videoMaxSizeInBytes)

        Sets the maximum size in bytes for recorded video files.Once this size is reached, the recording will automatically stop.Defaults to unlimited size. Use 0 or negatives to disable.

        Parameters:
        videoMaxSizeInBytes - The maximum video size in bytes
      • getVideoMaxSize

         long getVideoMaxSize()

        Returns the maximum size in bytes for recorded video files, or 0if no size was set.

      • setVideoMaxDuration

         void setVideoMaxDuration(int videoMaxDurationMillis)

        Sets the maximum duration in milliseconds for video recordings.Once this duration is reached, the recording will automatically stop.Defaults to unlimited duration. Use 0 or negatives to disable.

        Parameters:
        videoMaxDurationMillis - The maximum video duration in milliseconds
      • getVideoMaxDuration

         int getVideoMaxDuration()

        Returns the maximum duration in milliseconds for video recordings, or 0if no limit was set.

      • isTakingVideo

         boolean isTakingVideo()

        Returns true if the camera is currently recording a video

      • isTakingPicture

         boolean isTakingPicture()

        Returns true if the camera is currently capturing a picture

      • setDrawHardwareOverlays

         void setDrawHardwareOverlays(boolean on)

        Sets the overlay layout hardware canvas capture mode to allow hardwareaccelerated views to be captured in snapshots

        Parameters:
        on - true if enabled
      • getDrawHardwareOverlays

         boolean getDrawHardwareOverlays()

        Returns true if the overlay layout is set to capture the hardware canvasof child views

      • setFrameProcessingMaxWidth

         void setFrameProcessingMaxWidth(int maxWidth)

        Sets the max width for frame processing Frames.This option is only supported by CAMERA2 and will have no effecton other engines.

        Parameters:
        maxWidth - max width for frames
      • setFrameProcessingMaxHeight

         void setFrameProcessingMaxHeight(int maxHeight)

        Sets the max height for frame processing Frames.This option is only supported by CAMERA2 and will have no effecton other engines.

        Parameters:
        maxHeight - max height for frames
      • setFrameProcessingPoolSize

         void setFrameProcessingPoolSize(int poolSize)

        Sets the frame processing pool size. This is (roughly) the max number of Frame instances that can exist at a given moment in the frame pipeline,excluding frozen frames.Defaults to 2 - higher values will increase the memory usage with little benefit.Can be higher than 2 if setFrameProcessingExecutors is used.These values should be tuned together. We recommend setting a pool size that's equal tothe number of executors plus 1, so that there's always a free Frame for the camera engine.Changing this value after camera initialization will have no effect.

        Parameters:
        poolSize - pool size
      • setFrameProcessingExecutors

         void setFrameProcessingExecutors(int executors)

        Sets the thread pool size for frame processing. This means that if the processing rateis slower than the preview rate, you can set this value to something bigger than 1to avoid losing frames.Defaults to 1 and this should be OK for most applications.Should be tuned depending on the task, the processor implementation, and along with setFrameProcessingPoolSize. We recommend choosing a pool size that isequal to the executors plus 1.

        Parameters:
        executors - thread count
      • setFilter

         void setFilter(@NonNull() Filter filter)

        Applies a real-time filter to the camera preview, if it supports it.The only preview type that does so is currently GL_SURFACE.The filter will be applied to any picture snapshot taken with takePictureSnapshot and any video snapshot taken with takeVideoSnapshot.Use NoFilter to clear the existing filter,and take a look at the Filters class for commonly used filters.This method will throw an exception if the current preview does not support real-timefilters. Make sure you use GL_SURFACE (the default).

        Parameters:
        filter - a new filter
      • getFilter

        @NonNull() Filter getFilter()

        Returns the current real-time filter applied to the camera preview.This method will throw an exception if the current preview does not support real-timefilters. Make sure you use GL_SURFACE (the default).