有时候依赖于设备,onSurfaceChanged方法不止一次调用,这会导致相机预览崩溃(我正在使用camera2)。 我不知道如何解决这个问题。这是我的代码的一部分:
@Override
public synchronized void onSurfaceChanged(GL10 gl, int width, int height) {
// if(!(width == mWidth || height == mHeight)) {
mWidth = width;
mHeight= height;
Log.e("ex1", "onSurfaceChanged = " + width + ", height = " + height);
//generate camera texture------------------------
setupSurfaceTexture(width, height);
surfaceIsDestroyed = false;
//}
}
private void setupSurfaceTexture(final int width,final int height) {
System.out.println("setupSurfaceTexture is being called");
mCameraTexture.init();
//set up surface texture------------------
SurfaceTexture oldSurfaceTexture = mSurfaceTexture;
mSurfaceTexture = new SurfaceTexture(mCameraTexture.getTextureId());
mSurfaceTexture.setOnFrameAvailableListener(this);
if(oldSurfaceTexture != null) {
oldSurfaceTexture.release();
}
//get the camera orientation and display dimension, open camera------------
int orientation = mContext.getResources().getConfiguration().orientation;
float rotation = 90;
if((orientation == 1) && (newApi)) { // TODO: NEED TO BE CHANGED
isPortrait = true;
rotation = 0;
}
icam.openCamera(width, height, mSurfaceTexture);
System.out.println("Is new API: " + newApi);
if(mContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
Matrix.setRotateM(mOrientationM, 0, rotation, 0f, 0f, 1f);
if(newApi) {
icam.updateScaling(width, height, isPortrait);
mRatio[0] = icam.getCameraWidthOrScaleX();
mRatio[1] = icam.getCameraHeightOrScaleY();
} else {
icam.updateScaling(width, height, isPortrait);
mRatio[0] = icam.getCameraWidthOrScaleX();// * 1.0f/height;
mRatio[1] = icam.getCameraHeightOrScaleY();// * 1.0f/width;
}
} else {
Matrix.setRotateM(mOrientationM, 0, rotation, 0f, 0f, 1f);
if(newApi) {
mRatio[1] = icam.getCameraWidthOrScaleX();
mRatio[0] = icam.getCameraHeightOrScaleY();
} else {
mRatio[1] = icam.getCameraWidthOrScaleX();//*1.0f/height;
mRatio[0] = icam.getCameraHeightOrScaleY();//*1.0f/width;
}
}
Log.d("Rotation Portrait", mRatio[0] + "-----" + mRatio[1]);
//start render-----
requestRender();
surfaceSetuped = true;
}
答案 0 :(得分:1)
建议 harvey-slash 时,您可能无法在第二次调用onSurfaceChanged()
时重新初始化所有内容。表面的大小已经改变了 - 那又怎样?您可以选择更好地设置适合新宽高比的预览尺寸,或者强制布局适合您之前设置的预览尺寸(get LayoutParams
并设置负边距)。
另一个棘手的情况是,对onSurfaceChanged()
的重复调用是设备方向改变的结果。但即便如此,您仍可继续重复使用相机。