本文結合本人的開發實例,介紹如何實現攝像頭臨摹效果,即將攝像頭拍攝的畫面作為臨摹的物體投射到畫紙上,用戶可以在畫紙上繼續作畫,效果如圖1.
主要可以分成四步,第一步在AndroidManifest.xml文件裡添加對攝像機的使用許可。
<uses-permissionandroid:name="android.permission.CAMERA"/>
第二步在佈局文件裡使用framelayout,這樣可以實現兩個view疊在一起的效果,要保證兩個view的大小和位置相同。
[html] <span style="font-size:16px;"> <FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView
android:id="@+id/SurfaceView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<com.example.artist.PaintView
android:id="@+id/PaintView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</FrameLayout>
</span>
<span style="font-size:16px;"> <FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView
android:id="@+id/SurfaceView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<com.example.artist.PaintView
android:id="@+id/PaintView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</FrameLayout>
</span>
其中的surfaceview用來動態顯示攝像機當前拍攝的畫面,第三步需要打開攝像機並進行相關配置,然後開啟預覽。
[java]<span style="font-size:16px;">mSurfaceView = (SurfaceView)this.findViewById(R.id.sfView);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(SimplePaintActivity.this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mCamera = Camera.open();
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.setPreviewSize(dm.widthPixels, dm.heightPixels);
parameters.setPictureSize(dm.widthPixels, dm.heightPixels);
mCamera.setParameters(parameters);
try {
mCamera.setPreviewDisplay(mSurfaceHolder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
</span>
<span style="font-size:16px;">mSurfaceView = (SurfaceView)this.findViewById(R.id.sfView);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(SimplePaintActivity.this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mCamera = Camera.open();
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.setPreviewSize(dm.widthPixels, dm.heightPixels);
parameters.setPictureSize(dm.widthPixels, dm.heightPixels);
mCamera.setParameters(parameters);
try {
mCamera.setPreviewDisplay(mSurfaceHolder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
</span>
第四步需要改變com.example.artist.PaintView的背景透明度,PaintView是本人自己實現的一個view,在onTouchEvent函數和onDraw函數裡分別進行瞭觸摸響應和繪畫功能,是用來響應用戶畫畫的view,設置背景半透明的語句如下。
mBkColor = Color.argb(100, 255, 255, 255);
canvas.drawColor(mBkColor);
這樣,攝像頭臨摹效果就實現瞭,大功告成!
摘自 北京大學-Google Android實驗室