Android: Want to put an silhouette overlay on a Ca

2019-05-18 19:11发布

问题:

I'd like to know how I can put a silhouette on top of a camera preview. So far i've got the following example working, which just previews the Camera.

http://developer.android.com/reference/android/view/TextureView.html

I'm trying to have a Camera preview, where I got a silhouette shown so the person using the app gets an idea of where the picture should be taken, and then a button that when clicked, takes the picture, without the silhouette of course in the picture.

How can this be done? I can't seem to find any examples of how to put an overlay on top of a texture view.

回答1:

Using the example in the TextureView docs you've linked, we simply create a layout XML file to hold our TextureView and overlay ImageView in a FrameLayout. We then call the Activity's setContentView() method with this layout's Resource ID, instead of the dynamically-created TextureView in the example.

The layout file, main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextureView android:id="@+id/texture_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ImageView android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#00000000"
        android:src="@drawable/ic_launcher" />

</FrameLayout>

And the sample Activity:

public class LiveCameraActivity extends Activity
    implements TextureView.SurfaceTextureListener {

    private Camera mCamera;
    private TextureView mTextureView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTextureView = (TextureView) findViewById(R.id.texture_view);
        mTextureView.setSurfaceTextureListener(this);
    }

    // The TextureView.SurfaceTextureListener methods
    // are the same as shown in the example.

    ...
}

The overlay ImageView in the layout uses the default launcher icon as its source image, as it has transparency, at least on my IDE. You would later replace this image with your silhouette. The ImageView, being listed after the TextureView, will appear on top of it, because Views are drawn with respect to their z-order in the same order they're listed in the layout, with the first View listed being on the bottom; i.e., the farthest away from you on the z-axis.

In the Activity, we're just loading the layout as the content View, and getting a reference to the TextureView created there. Everything else is the same.