在自定义相机Kotlin中预览

时间:2018-10-11 20:35:32

标签: android kotlin camera

设计自定义相机。预览出现问题。 我有2个课程: CameraActivity,CameraPreview 。与here相同。

捕获照片后,照片被保存,并且预览停止并且什么也没有发生,但是再次单击后,没有照片,并且预览将还原工作。

如何解决?也许我没有正确使用预览类?

CameraActivity.kt

class CameraActivity(context: Context, frame : FrameLayout) {

    private var mCamera: Camera? = null       
    private lateinit var mPreview: SurfaceView

    init{
        setCamerasId()
        initCamera(mCameraIdBack) 
    }
    private fun getCameraInstance(id : Int): Camera? {
        return try {
            Camera.open(id)
        } catch (e: Exception) {null}
    }

    private fun initCamera(id : Int){
        mCamera = getCameraInstance(id)
        mPreview = CameraPreview(mContext, mCamera!!)
        mFrame.addView(mPreview)
    }

    fun takePhoto() {
        try {
            mCamera?.takePicture(null, null, mPicture)
        } catch (e : Exception){
            Toast.makeText(mContext, "Error capture photo", Toast.LENGTH_SHORT).show()
        }
        try {
            mCamera?.startPreview()
        } catch (e : Exception){
            Toast.makeText(mContext, "Error start preview", Toast.LENGTH_SHORT).show()
        }

        mPictureFile = null
    }
    private val mPicture = Camera.PictureCallback { data, _ ->
        mPictureFile = getOutputMediaFile() ?: run {
            return@PictureCallback
        }
        try {
            Toast.makeText(mContext, "Success", Toast.LENGTH_SHORT).show()
            val fos = FileOutputStream(mPictureFile)
            fos.write(data)
            fos.close()
            addImageToGallery(mPictureFile!!.path, mContext)
            callShutterSound()

        } catch (e: Exception) {}
    }

CameraPreview.kt

class CameraPreview(
        private var mContext: Context,
        private var mCamera: Camera
) : SurfaceView(mContext), SurfaceHolder.Callback {
    private val mHolder: SurfaceHolder = holder.apply {
        addCallback(this@CameraPreview)
        setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        mCamera.apply {
            try {
                setParameters()
                setPreviewDisplay(holder)
                startPreview()
            } catch (e: Exception) {}
        }
    }
    override fun surfaceDestroyed(holder: SurfaceHolder) {
        mCamera.release()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, w: Int, h: Int) {
        if (mHolder.surface == null) {
            return
        }
        try {
            mCamera.stopPreview()
        } catch (e: Exception) {}
        mCamera.apply {
            try {
                setParameters()
                setPreviewDisplay(mHolder)
                startPreview()
            } catch (e: Exception) {}
        }
    }
}

1 个答案:

答案 0 :(得分:0)

需要延迟才能正确显示预览。