让我的SurfaceView
显示我的相机预览时遇到一些麻烦。我已经在这里查看了一些问题,谷歌也提出了一些问题,但我认为这可能是我的一个小错误,我只是没有看到。
代码
public class RoofPitchActivity extends Activity implements SensorEventListener {
...
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_roof_pitch);
initViews();
}
private void initViews() {
...
Preview preview = new Preview(this);
mCamera = Camera.open();
preview.setCamera(mCamera);
}
...
...
class Preview extends ViewGroup implements SurfaceHolder.Callback {
public Preview(Context context) {
super(context);
mSurfaceView = (SurfaceView) findViewById(R.id.preview);
mSurfaceView = new SurfaceView(context);
addView(mSurfaceView);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
}
public void setCamera(Camera camera) {
if (mCamera == camera) {
return;
}
stopPreviewAndFreeCamera();
mCamera = camera;
if (mCamera != null) {
requestLayout();
try {
mCamera.setPreviewDisplay(mSurfaceHolder);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
}
private void stopPreviewAndFreeCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mCamera.startPreview();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mSurfaceView.getWidth(), mSurfaceView.getHeight());
requestLayout();
mCamera.setParameters(parameters);
mCamera.startPreview();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
mCamera.stopPreview();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
}
}
因此,当活动启动时,SurfaceView
为黑色。相机似乎没有将预览渲染到SurfaceView
上。我敢肯定有一些我想念的小东西,或者这只是对它如何运作的一个有趣的误解。一个新的眼睛有一点点解释将非常感激。感谢
答案 0 :(得分:1)
所以我的问题的答案最终是特定于设备的。代码是可以接受的,但我用来调试的设备是Nexus 7.这意味着摄像头是朝前的,正常的摄像头调用不起作用。有关这方面的有趣且有趣的读物可以在in this article
找到Camera.open();
不起作用。你必须使用
Camera.open(0);
所以我的代码最终得到了相机的条件检查,现在它工作正常。
喜欢这样
public void setCamera() {
stopPreviewAndFreeCamera();
PackageManager pm = getPackageManager();
boolean backCamera = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
boolean frontCamera = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);
if (frontCamera) {
mCamera = Camera.open(0);
} else if (backCamera) {
mCamera = Camera.open();
}
if (mCamera != null) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mSurfaceView.getWidth(), mSurfaceView.getHeight());
requestLayout();
try {
mCamera.setParameters(parameters);
mCamera.setPreviewDisplay(mSurfaceHolder);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
}