我创建了一个CameraSurfaceView.java
我在containerView中添加了cameraSurfaceView。
另外,我输入许可和功能。
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
但这是行不通的。
我该如何解决?
这是我的示例代码,
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/cameraPreview"
android:layout_width="350dp"
android:layout_height="350dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.widget.FrameLayout;
public class MainActivity extends Activity {
FrameLayout containerView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFormat(PixelFormat.UNKNOWN);
containerView= (FrameLayout)findViewById(R.id.camerapreview);
CameraSurfaceView cameraSurfaceView = new CameraSurfaceView(MainActivity.this);
containerView.addView(cameraSurfaceView);
}
}
CameraSurfaceView.java
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
Camera camera = null;
SurfaceHolder surfaceHolder;
boolean previewing = false;
public CameraSurfaceView(Context context) {
super(context);
surfaceHolder = getHolder();
if (surfaceHolder != null) {
surfaceHolder.addCallback(this);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
camera.setDisplayOrientation(90);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
谢谢。
最佳答案
您还需要在CameraSurfaceView
中传递相机对象
public CameraSurfaceView(Context context,Camera camera) {
super(context);
this.camera = camera;
surfaceHolder = getHolder();
if (surfaceHolder != null) {
surfaceHolder.addCallback(this);
}
}
在您的主要活动中,您需要打开相机//初始化,
private Camera mCamera;
CameraSurfaceView cameraSurfaceView = new CameraSurfaceView(MainActivity.this,mCamera);
关于android - Android中的自定义相机类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35079352/