Is it possible to crop camera preview?

You can do this without overlay views (which won't work in all situations).

Subclass ViewGroup, add the SurfaceView as the only child, then:

  1. in onMeasure supply the cropped dimensions you want.
  2. in onLayout, layout the SurfaceView with the un-cropped dimensions.

basically,

public class CroppedCameraPreview extends ViewGroup {
  private SurfaceView cameraPreview;
  public CroppedCameraPreview( Context context ) {
    super( context );
    // i'd probably create and add the SurfaceView here, but it doesn't matter
  }
  @Override
  protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
    setMeasuredDimension( croppedWidth, croppedHeight );
  }
  @Override
  protected void onLayout( boolean changed, int l, int t, int r, int b ) {
    if ( cameraPreview != null ) {
      cameraPreview.layout( 0, 0, actualPreviewWidth, actualPreviewHeight );
    }
  }
}

Not directly. Camera API does now allow for offsets, and will squeeze image into surface holder. But you can work around by placing overlays (other views) over it.


You could put the camera preview (SurfaceView) inside a LinearLayout that is inside a ScrollView. When the camera output is bigger than the LinearLayout you set you can programmatically scroll it and disable user scroll. This way you can emulate camera cropping in an easy way:

<ScrollView 
                     android:id="@+id/scrollView"
                     android:layout_width="640dip"
                     android:layout_height="282dip"
                     android:scrollbars="none"
                     android:fillViewport="true">

                        <LinearLayout
                                android:id="@+id/linearLayoutBeautyContent"
                                android:layout_width="fill_parent"
                                android:layout_height="fill_parent"
                                android:orientation="vertical">

                                <SurfaceView
                                            android:layout_width="match_parent"
                                            android:layout_height="match_parent"
                                            android:id="@+id/surfaceViewBeautyCamera"/>
                      </LinearLayout>
</ScrollView>