VR 即 Virtual Reality 虚拟现实。 虚拟现实技术是一种可以创建和体验虚拟世界的计算机仿真系统它利用计算机生成一种模拟环境是一种多源信息融合的交互式的三维动态视景和实体行为的系统仿真使用户沉浸到该环境中。
那么,如何在 Android 中去开发 VR 功能的 APP 呢?我们利用谷歌提供的开源 SDK 来实现实现一个 360° 全景图片的功能。
效果图VR
- 支持水平触摸滑动
- 陀螺仪传感
1. 添加依赖
implementation 'com.google.vr:sdk-panowidget:1.180.0'
注意支持的最小 SDK
minSdkVersion 19 targetSdkVersion 25
2. 布局文件
<com.google.vr.sdk.widgets.pano.VrPanoramaView android:id="@+id/vrPanoramaView" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_aspectRatio="178%" app:layout_widthPercent="100%" tools:ignore="MissingClass" />
3. 加载 360° 全景图片
... vrPanoramaView = findViewById(R.id.vrPanoramaView); vrPanoramaView.setTouchTrackingEnabled(true); vrPanoramaView.setFullscreenButtonEnabled(true); vrPanoramaView.setInfoButtonEnabled(false); vrPanoramaView.setStereoModeButtonEnabled(false); PanoramaImageModel model = ModelUtil.getPanoramaImageList().get(currPosition); loadPanoramaImage(model); ... private void loadPanoramaImage(PanoramaImageModel model) { loadPanoramaImage(getBitmapFromAssets(model.assetName)); tvTitle.setText(model.title); } private void loadPanoramaImage(Bitmap bitmap) { if (bitmap == null) return; VrPanoramaView.Options options = new VrPanoramaView.Options(); options.inputType = VrPanoramaView.Options.TYPE_MONO; vrPanoramaView.loadImageFromBitmap(bitmap, options); } private Bitmap getBitmapFromAssets(String fileName) { if (TextUtils.isEmpty(fileName)) return null; try { InputStream inputStream = getAssets().open(fileName); return BitmapFactory.decodeStream(inputStream); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onResume() { super.onResume(); vrPanoramaView.resumeRendering(); } @Override protected void onPause() { super.onPause(); vrPanoramaView.pauseRendering(); } @Override protected void onDestroy() { vrPanoramaView.shutdown(); super.onDestroy(); }
源码地址:DroidVR
