你如何使用Deprecated Camera API FrameLayout,让你的相机预览有圆角?

时间:2017-05-16 23:47:23

标签: background deprecated

我正在尝试将FrameLayout与Deprecated Camera API一起使用,根据android developer's site上的文档,我试图让应用程序内的相机预览有圆角。

Signup_Selfie_shot

package com.novateur.realtime;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Environment;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;


import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

import org.w3c.dom.Text;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.R.attr.data;
import static android.R.attr.id;

public class Signup_Selfie_shot extends Activity {

    private Camera mCamera;
    private CameraPreview mPreview;

 //   private StorageReference mStorage;

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    private Button btn1;

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

        Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/LeagueSpartan-Bold.ttf");

        //mStorage = FirebaseStorage.getInstance().getReference();

        TextView tx1 = (TextView) findViewById(R.id.smileText);
        tx1.setTypeface(custom_font);

        TextView tx2 = (TextView) findViewById(R.id.camTextView);
        tx2.setTypeface(custom_font);

        btn1 = (Button) findViewById(R.id.tapPicButton);
        btn1.setTypeface(custom_font);

        Button btn2 = (Button) findViewById(R.id.camNextButton);
        btn2.setTypeface(custom_font);




        // Create an instance of Camera----------------------------------------
        mCamera = openFrontFacingCameraGingerbread();
//
        //// Create our Preview view and set it as the content of our activity.
        mPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.cameraView);
        preview.addView(mPreview);
        //----------------------------------------------------------------------
        // Add a listener to the Capture button



        btn1.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // get an image from the camera
                        mCamera.takePicture(null, null, mPicture);
                    }
                }
        );


    }

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance

            if (c != null){
                Camera.Parameters params = c.getParameters();
                c.setParameters(params);
            }
        }
        catch (Exception e){
            Log.d("DEBUG", "Camera did not open");
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    PictureCallback mPicture = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
            if (pictureFile == null) {
                return;
            }
            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
        }
    };

    private static File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "MyCameraApp");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_"+ timeStamp + ".jpg");
        } else if(type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_"+ timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
    private Camera openFrontFacingCameraGingerbread() {
        int cameraCount = 0;
        Camera cam = null;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();
        for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
            Camera.getCameraInfo(camIdx, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                try {
                    cam = Camera.open(camIdx);
                } catch (RuntimeException e) {
                    Log.e("MyCameraApp", "Camera failed to open: " + e.getLocalizedMessage());
                }
            }
        }

        return cam;
    }
}

布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.novateur.realtime.Signup_Selfie_shot">

    <TextView
        android:id="@+id/smileText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Smile,"
        android:textSize="20sp"
        android:textColor="#000000"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="50dp"
        app:layout_constraintHorizontal_bias="0.502" />

    <TextView
        android:id="@+id/camTextView"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:text="You're on Camera "
        android:textSize="20sp"
        android:textColor="#000000"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/smileText" />

    <FrameLayout
        android:id="@+id/cameraSignUpPort"
        android:layout_width="252dp"
        android:layout_height="273dp"
        android:layout_marginTop="22dp"
        android:background="@drawable/view_red_bordered"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/camTextView" >

        <FrameLayout
            android:id="@+id/cameraView"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </FrameLayout>
    </FrameLayout>

    <Button
        android:id="@+id/camNextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="Next"
        android:textSize="18sp"
        android:textAllCaps="false"
        android:textColor="#808080"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="50dp"
        app:layout_constraintTop_toBottomOf="@+id/tapPicButton"
        style="?android:attr/borderlessButtonStyle" />

    <Button
        android:id="@+id/tapPicButton"
        android:layout_width="245sp"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:background="@drawable/view_red_filled"
        android:text="Tap to take a pic!"
        android:textSize="16sp"
        android:textColor="#ffffff"
        android:textAllCaps="false"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cameraSignUpPort" />
</android.support.constraint.ConstraintLayout>

cameraPreview

package com.novateur.realtime;

        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;

        import android.content.Context;
        import android.graphics.Canvas;
        import android.graphics.Color;
        import android.graphics.Paint;
        import android.hardware.Camera;
        import android.hardware.Camera.PreviewCallback;
        import android.util.Log;
        import android.view.SurfaceHolder;
        import android.view.SurfaceView;

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Camera mCamera;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d("DEBUG", "Error setting camera preview: " + e.getMessage());
        }


    }

    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d("DEBUG", "Error starting camera preview: " + e.getMessage());
        }
    }
}

0 个答案:

没有答案