游戏开发2_05 多媒体---图像采集
package wyf.ytl;
import java.io.IOException;//引入相关类
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
public class Sample_2_12 extends Activity implements SurfaceHolder.Callback{
Camera myCamera;//Camera的引用
SurfaceView mySurfaceView;//SurfaceView的引用
SurfaceHolder mySurfaceHolder;//SurfaceHolder的引用
Button button1;//按钮的引用
Button button2;
boolean isPreview = false;//是否在浏览中
public void onCreate(Bundle savedInstanceState) {//重写的onCreate方法
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mySurfaceView = (SurfaceView) findViewById(R.id.surfaceView);//得到SurfaceView的引用
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);//得到两个按钮的应用
mySurfaceHolder = mySurfaceView.getHolder();//获得SurfaceHolder
mySurfaceHolder.addCallback(this);
mySurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
button1.setOnClickListener(new Button.OnClickListener(){//打开的按钮监听
public void onClick(View arg0) {
initCamera();
}
});
button2.setOnClickListener(new Button.OnClickListener(){//关闭的按钮监听
public void onClick(View arg0) {
if(myCamera != null && isPreview){//正在显示时
myCamera.stopPreview();
myCamera.release();
myCamera = null;
isPreview = false;
}
}
});
}
public void initCamera(){//初始化相机资源
if(!isPreview){
myCamera = Camera.open();
}
if(myCamera != null && !isPreview){
try {
myCamera.setPreviewDisplay(mySurfaceHolder);
myCamera.startPreview();//立即运行Preview
} catch (IOException e) {
e.printStackTrace();//打印错误信息
}
isPreview = true;
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
<?xml version="1.0" encoding="utf-8"?><!-- XML的版本以及编码方式 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
><!--添加一个垂直的线性布局 -->
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="320px"
android:layout_height="240px"
/><!--添加一个SurfaceView用于浏览 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
><!--添加一个线性布局 -->
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开"
/><!--添加一个按钮 -->
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="关闭"
/><!--添加一个按钮 -->
</LinearLayout>
</LinearLayout>