且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android相机预览看起来很奇怪

更新时间:2021-08-22 23:36:58

相机预览总是填满显示它的SurfaceView.如果 m_surfaceView 的纵横比与相机的纵横比不匹配,则会拉伸预览.

The camera preview always fills up the SurfaceView showing it. If the aspect ratio of m_surfaceView doesn't match with the camera's aspect ratio, the preview will be stretched.

您需要创建与纵横比匹配的 m_surfaceView.这意味着,您需要从代码创建它,而不是从布局 XML 文件.

You'll need to create m_surfaceView matching the aspect ratio. That means, you'll need to create it from code, not from layout XML file.

您可以在 android 示例项目中找到一个示例项目 APIDemos.在项目中有一个名为 CameraPreview 的东西.这有一个很好的演示,用于在 SurfaceView 中设置相机预览.它有一个类extends ViewGroup,并从代码中添加SurfaceView 作为其子项.onMeasure() 方法已被重写以确定 SurfaceView 的高度和宽度,因此保留了纵横比.看一下项目,希望清楚.

There is a sample project APIDemos that you'll find in android sample projects. In the project there is a thing named CameraPreview. This one has a good demonstration for setting up camera preview in a SurfaceView. It has a class that extends ViewGroup, and adds the SurfaceView as its child from the code. The onMeasure() method has been overridden to determine the height and width of the SurfaceView, so the aspect ratio is preserved. Take a look on the project, and I hope it will be clear.

[抱歉,我无法在此处发布链接 - 应该是链接,但我发现它坏了.但是如果您已经安装了带有 Android SDK 的示例项目,您可以在示例中找到该项目.打开一个新的 Android 示例项目,选择 APIDemos,然后查找名为 CameraPreview 的类.据我记得,它应该在 com.example.android.apis.graphics 包中.]

[Sorry I couldn't post the link here - this is supposed to be the link, but I found it broken. But if you have installed the sample projects with the Android SDK, you can find the project in the samples. Open a new Android Sample Project, select APIDemos, then look for a class named CameraPreview. It should be in the package com.example.android.apis.graphics, as far as I remember.]