《Andorid》TextureView 获取Camera相机简单用法

第一步获取权限如果安卓系统6.0以下的在Androidmanifest.xml添加

            <uses-permission android:name="android.permission.CAMERA"/>

如果6.0以上就动态获取

代码例子:
@SuppressLint("NewApi")
public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {
    private TextureView textureView;
    private android.hardware.Camera mCamera;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        textureView=new TextureView(this);
        textureView.setSurfaceTextureListener(this);
        setContentView(textureView);
        if (!(this.checkSelfPermission("android.permission.CAMERA")== PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String []{"android.permission.CAMERA"},1);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @org.jetbrains.annotations.NotNull String[] permissions, @NonNull @org.jetbrains.annotations.NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==1&&this.checkSelfPermission("android.permission.CAMERA")== PackageManager.PERMISSION_GRANTED){
            Toast.makeText(this,"获取权限成功",Toast.LENGTH_SHORT).show();
        }

    }

    //当TextureView准备好使用Surface的SurfaceTexture时调用
    @Override
    public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
        mCamera=android.hardware.Camera.open();
        //设置预览大小
        Camera.Size previewSize = mCamera.getParameters().getPreviewSize();
        //textureView设置为相机预览大小
        textureView.setLayoutParams(new FrameLayout.LayoutParams(
                previewSize.width, previewSize.height, Gravity.CENTER));
        try {
            //设置surface
            mCamera.setPreviewTexture(surface);
        } catch (IOException t) {
        }
        //开始捕获
        mCamera.startPreview();
        //透明度
        textureView.setAlpha(1.0f);
        //旋转
        textureView.setRotation(90.0f);

    }

    //SurfaceTexture的缓冲区大小更改时调用。
    @Override
    public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

    }

    //在将SurfaceTexture要销毁指定的对象时调用
    @Override
    public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
        //停止捕获
        mCamera.stopPreview();
        mCamera.release();
        return true;

    }

    //SurfaceTexture通过更新指定的值时调用
    @Override
    public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

    }

 



《Andorid》TextureView 获取Camera相机简单用法

上一篇:存在Iframe定位的相关问题


下一篇:节流防抖