Android游戏开发学习笔记(四):Camera图像采集
一、为相机添加权限。在AndroidManifest.xml文件的</application>之后,添加相机使用的权限:
<uses-permission android:name="android.permission.CAMERA"/>
二、编写布局文件main.xml,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Su易做图ceView
android:id="@+id/su易做图ceView"
android:layout_width="320px"
android:layout_height="240px"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开"
/>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="关闭"
/>
</LinearLayout>
</LinearLayout>
三、编写MainActivity.java代码。
package game.test;
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.Su易做图ceHolder;
import android.view.Su易做图ceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements Su易做图ceHolder.Callback {
Camera myCamera;
Su易做图ceView mySu易做图ceView;
Su易做图ceHolder mySu易做图ceHolder;
Button btn1, btn2;
boolean isPreview = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mySu易做图ceView = (Su易做图ceView) findViewById(R.id.su易做图ceView);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
mySu易做图ceHolder = mySu易做图ceView.getHolder();
mySu易做图ceHolder.addCallback(this);
mySu易做图ceHolder.setType(Su易做图ceHolder.SURFACE_TYPE_PUSH_BUFFERS);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
initCamera();
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
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(mySu易做图ceHolder);
myCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
isPreview = true;
}
}
@Override
public void su易做图ceCreated(Su易做图ceHolder holder) {
// TODO Auto-generated method stub
}
@Override
public void su易做图ceChanged(Su易做图ceHolder holde
补充:移动开发 , Android ,