所需要的VR运行库可在
https://github.com/googlevr/gvr-android-sdk/下载
进入正题:
1. 在项目main文件夹下新建资产目录 assets并把图片放入该文件下:
tips:文件夹命名必须是assets,否者会出现空指针错误。
2.以module的形式导入VR项目依赖的library库,分别是必要的库common,commonwidge,和可选择的,例如 panowidget(全景)。
快捷键(ctrl+shift+alt+s),实现module相关联。
在项目里的build.gradle文件里添加: compile 'com.google.protobuf.nano:protobuf-javanano:3.0.0-alpha-7
在AnroidManifest.xml文件下添加:
android
:largeHeap=
"true"
防止资源过大,出现out of memory错误。
完成xml布局,VrPanoramaView。
由于Vr资源量大,所以加载到子线程中进行主线程来显示图片。使用一个异步线程AsyncTask或EventBus技术进行
代码如下:
public class MainActivity extends AppCompatActivity { private VrPanoramaView vrp; private ImageLoader img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { vrp= (VrPanoramaView) findViewById(R.id.vr_button); // 隐藏掉VR效果左下角信息按钮显示 vrp.setInfoButtonEnabled(false); // 隐藏掉VR效果右下角信全屏按钮显示、 vrp.setFullscreenButtonEnabled(false); //切换VR模式 (手机横放模式) vrp.setDisplayMode(VrWidgetView.DisplayMode.FULLSCREEN_STEREO); //设置时间监听 vrp.setEventListener(new MyListener()); img = new ImageLoader(); img.execute(); // 设置VR运行状态监听 } //因为读取VR资源是耗时操作,VR图片资源较大,所以不能在主线程做读取操,但是在主线成才能做UI更新,我们使用AsyncTask private class ImageLoader extends AsyncTask<Void ,Void,Bitmap>{ //该方法子啊子线程运行,从本地文件将资源加载到内存中 @Override protected Bitmap doInBackground(Void... params) { //从资源目录拿到资源,返回结果是字节流 try { InputStream open = getAssets().open("andes.jpg"); //把字节流转化为bitmap对象 Bitmap bitmap = BitmapFactory.decodeStream(open); return bitmap; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap bitmap) { //创建VrPanoramaView.Options,决定显示VR是立体效果,还是普通效果 VrPanoramaView.Options options = new VrPanoramaView.Options(); //TYPE_STEREO_OVER_UNDER立体效果, TYPE_MONO普通效果 options.inputType=VrPanoramaView.Options.TYPE_STEREO_OVER_UNDER; //使用VR控件显示效果 参数1:btmap对象 参数2:VrPanoramaView.Options对象,决定显示效果; vrp.loadImageFromBitmap(bitmap,options); super.onPostExecute(bitmap); }
}
8. 以下为优化()
@Override protected void onPause() { //暂停渲染和显示 vrp.pauseRendering(); super.onPause(); } @Override protected void onResume() { //继续渲染和显示 vrp.resumeRendering(); super.onResume(); } //当activity销毁时,回调 @Override protected void onDestroy() { super.onDestroy(); //关闭渲染效果 vrp.shutdown(); if(img!=null){ //在退出activity时,如果异步任务没有取消,就取消 if(!img.isCancelled()){ img.cancel(true); } } } //vr运行状态监听类 private class MyListener extends VrPanoramaEventListener{ //当VR视图加载失败回调 @Override public void onLoadError(String errorMessage) { Toast.makeText(MainActivity.this,"shibai",Toast.LENGTH_SHORT).show(); } //当VR视图加载成功回调 @Override public void onLoadSuccess() { Toast.makeText(MainActivity.this,"chenggong",Toast.LENGTH_SHORT).show(); } } }
以上就是Android建立的VR项目,如有不当之处,请见谅。
需在真机上测试。
转载请注明原文地址: https://ju.6miu.com/read-5695.html