为什么这个相机预览表面不起作用

时间:2015-04-06 12:57:56

标签: android android-camera

为什么它不起作用?并在活动中显示黑色表面: 我想在我的活动中只显示相机 谢谢你的帮助

import android.content.Context;

import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;

import java.io.IOException;
import java.util.List;

/**
 * Created by AMMR-USERNAME on 4/6/2015.
 */
public class CameraSurface extends SurfaceView implements SurfaceHolder.Callback{

    SurfaceHolder surfaceHolder;
    Camera camera;
    List<Camera.Size> localSize;

    public CameraSurface(Context context) {
        super(context);
        Init(context);
    }

    public CameraSurface(Context context, AttributeSet attrs) {
        super(context, attrs);
        Init(context);
    }

    public CameraSurface(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        Init(context);
    }

    void Init(Context context)
    {


        surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        SafeCameraOpen(Camera.CameraInfo.CAMERA_FACING_FRONT);


    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        requestLayout();;
        camera.startPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if(camera != null)
            camera.stopPreview();
    }



    void StopPreviewAndFreeCamera()
    {
        if(camera != null)
        {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    boolean SafeCameraOpen(int id)
    {
        boolean qOpened = false;
        try
        {
            ReleaseCameraAndPreview();
            SetCamera(Camera.open(id));
            qOpened = (camera != null);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return qOpened;
    }

    void ReleaseCameraAndPreview()
    {
        SetCamera(null);
        if(camera != null)
        {
            camera.release();
            camera = null;
        }
    }


    void SetCamera(Camera _camera)
    {
        if(_camera == camera)
            return;
        StopPreviewAndFreeCamera();
        camera = _camera;
        if(camera != null)
        {
            localSize = camera.getParameters().getSupportedPreviewSizes();
            requestLayout();

            try {
                camera.setPreviewDisplay(surfaceHolder);
            } catch (IOException e) {
                e.printStackTrace();
            }

            camera.startPreview();
        }
    }
}

我用这个:  http://developer.android.com/training/camera/cameradirect.html 感谢。

0 个答案:

没有答案