您好我做了一个简单的相机应用程序,只有一个框架布局内的表面视图,最初预览占据了屏幕的整个宽度但稍后当我们按下主页按钮并从背景中取出应用程序时,只有一小部分它的颜色为黑色的屏幕,如附图所示。
代码:
public void setmCamera(Camera mCamera) {
this.mCamera = mCamera;
/*if (mHolder != null) {
mHolder.addCallback(this);
}*/
}
public CameraView(Context context) {
super(context);
this.context = context;
mHolder = getHolder();
mHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
/*getLayoutParams().height = ((MainActivity) context).getHeight();
getLayoutParams().width = ((MainActivity) context).getWidth();*/
//invalidate();
if (mCamera != null && !previewRunning) {
mCamera.stopPreview();
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
}
} catch (IOException e) {
Log.d("Tag", "Error setting camera preview: " + e.getMessage());
}
Log.d("Tag", "surfaceCreated: ");
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
/*getLayoutParams().height = ((MainActivity) context).getHeight();
getLayoutParams().width = ((MainActivity) context).getWidth();*/
// stop preview before making changes
if (mCamera != null) {
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
previewRunning = true;
} catch (Exception e) {
Log.d("Tag", "Error starting camera preview: " + e.getMessage());
}
}
Log.d("Tag", "surfaceChanged: " + width + " " + height);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
previewRunning = false;
Log.d("Tag", "surfaceDestroyed: ");
}
public void startUserPreview() {
mHolder = getHolder();
mHolder.addCallback(this);
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(mHolder);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void stopUserPreview() {
mHolder.addCallback(null);
}
SurfaceView类:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/surface_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
布局:
{{1}}