Java Android-如何使用camera getSupportedPreviewSizes()进行纵向定位
我正在尝试在活动中嵌入相机预览。而且只有纵向的。问题是预览会被拉伸 我已经试过挑选最合适的尺寸了。但问题是Java Android-如何使用camera getSupportedPreviewSizes()进行纵向定位,java,android,user-interface,camera,landscape-portrait,Java,Android,User Interface,Camera,Landscape Portrait,我正在尝试在活动中嵌入相机预览。而且只有纵向的。问题是预览会被拉伸 我已经试过挑选最合适的尺寸了。但问题是getSupportedPreviewSizes()中所有受支持的预览大小都返回横向大小。因此,根据我的代码选择合适的尺寸是行不通的 我的布局XML: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
getSupportedPreviewSizes()
中所有受支持的预览大小都返回横向大小。因此,根据我的代码选择合适的尺寸是行不通的
我的布局XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_take_attendance"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:orientation="vertical"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.lab.rafael.smartattendance.TakeAttendanceActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/take_attendance_label"
android:id="@+id/take_attendance_label"
android:layout_marginBottom="@dimen/activity_vertical_margin"/>
<!-- camera preview container -->
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/red"
android:id="@+id/take_attendance_scan_qr_frame"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/take_attendance_manual_text"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/take_attendance_manual_button"
android:id="@+id/take_attendance_manual_button"/>
</LinearLayout>
</LinearLayout>
以下图像是由这些值生成的:
Specified resolution from measureSpecWidth/Height = `984x1335`
Returned from getOptimalSize() = `1600x1200`.
因为提供的supportedPreviewSizes
用于横向而不是纵向
//in getOptimalSize(int width, int height)
//isCameraOnSide() is a new method you should implement
//return true iff the camera is mounted on the side compared to
//the phone's natural orientation.
double targetRatio = (isCameraOnSide()) ? (double) height / width
: (double) width / height,
optimalRatio = 0.0,
acceptableRatioMargin = 0.1,
minDiff = Double.MAX_VALUE;
for(Camera.Size size : supportedSizes) {
optimalRatio = (double) size.width / size.height;
if(Math.abs(optimalRatio - targetRatio) < acceptableRatioMargin) {
if(Math.abs(height - size.height) < minDiff) {
minDiff = Math.abs(height - size.height);
optimalSize = size;
}
}
}
结果如下:
我和一年前一样有同样的问题。另外,我还得处理前后摄像头的问题。关于代码我记得不多,但我在发布此答案之前尝试过,它仍然像一个符咒一样工作。
希望你能挖掘和比较你的代码。我可以分享更多的代码,如果你只是一些工作;)
/**
*围绕摄影机的简单包装和渲染摄影机居中预览的SurfaceView
*浮出水面。我们需要将SurfaceView置于中心位置,因为并非所有设备都有摄像头
*支持与设备显示器具有相同纵横比的预览大小。
*/
公共类预览扩展视图组实现SurfaceHolder.Callback{
SurfaceView mSurfaceView;
表面粗糙度;
相机。大小mPreviewSize;
列出MSSupportedPreviewsizes;
麦克默拉照相机;
私人语境;
麦卡默雷德私人酒店;
公共布尔使用前摄像头;
公共预览(上下文上下文,int-cameraId){
超级(上下文);
this.context=上下文;
mCameraId=cameraId;
使用前摄像头=真;
mSurfaceView=新的SurfaceView(上下文);
addView(mSurfaceView);
//安装SurfaceHolder.Callback,以便在
//创建和破坏下垫面。
mHolder=mSurfaceView.getHolder();
mHolder.addCallback(this);
}
公共摄像机(摄像机){
mCamera=摄像机;
if(mCamera!=null){
mSupportedPreviewSizes=mCamera.getParameters().getSupportedPreviewSizes();
requestLayout();
}
}
公共摄像机(摄像机){
设置摄像机(摄像机);
试一试{
摄像头。设置预览显示(mHolder);
}捕获(IOException异常){
android.util.Log.e(IdelityConstants.DEBUG_IDELITY_KEY_Log,“setPreviewDisplay()引起的IOException”,异常);
}
Camera.Parameters=Camera.getParameters();
parameters.setPreviewSize(mPreviewSize.width、mPreviewSize.height);
requestLayout();
设置参数(参数);
}
@凌驾
测量时的保护空隙(内部宽度测量等级、内部高度测量等级){
//我们故意忽略儿童的测量,因为这是一种
//包装到将摄影机预览居中的SurfaceView
//我想把它拉长。
int width=MeasureSpec.getSize(widthmasurespec);
int height=MeasureSpec.getSize(heightMeasureSpec);
//我必须称之为
设置测量尺寸(宽度、高度);
if(mSupportedPreviewSizes!=null){
mPreviewSize=getOptimalPreviewSize(MSSupportedPreviewSize、宽度、高度);
}
}
@凌驾
仅受保护的void布局(布尔值已更改、int l、int t、int r、int b){
如果(已更改&&getChildCount()>0){
最终视图子对象=getChildAt(0);
最终整数宽度=r-l;
最终内部高度=b-t;
int previewWidth=宽度;
亮度=高度;
if(mPreviewSize!=null){
/**
*在莫多景观和卢埃戈托卡的卡马拉,计算的结果是一致的
*在坎比亚多斯的瓦洛雷斯河上,卡马拉河是一条河流。
*/
previewWidth=mPreviewSize.height;
PreviewView=mPreviewSize.width;
}
//将子曲面视图居中放置在父曲面视图中。
if(宽度*预览宽度<高度*预览宽度){
最终整数缩放儿童宽度=预览宽度*高度/预览宽度;
布局((宽度-scaledChildWidth)/2,0,
(宽度+缩放儿童宽度)/2,高度);
}否则{
最终int scaledChildHeight=预览视图*宽度/预览宽度;
布局(0,(高度-缩放儿童高度)/2,
宽度(高度+缩放儿童高度)/2);
}
}
}
已创建的公共空白表面(表面持有人){
//曲面已创建,获取摄影机并告知其位置
//画。
试一试{
if(mCamera!=null){
mCamera.setPreviewDisplay(支架);
}
}捕获(IOException异常){
android.util.Log.e(IdelityConstants.DEBUG_IDELITY_KEY_Log,“setPreviewDisplay()引起的IOException”,异常);
}
}
公共空间表面覆盖(表面覆盖物持有人){
//当我们返回时,曲面将被破坏,因此请停止预览。
//if(mCamera!=null){
//mCamera.stopPreview();
// }
}
私人相机。大小getOptimalPreviewSize(列表大小,整数w,整数h){
最终双纵横比公差=0.1;
双目标率=(双)w/h;
如果(size==null)返回null;
照相机。大小优化大小=空;
double minDiff=double.MAX_值;
int targetHeight=h;
//尝试找到与纵横比和大小匹配的大小
用于(相机尺寸:尺寸){
双倍比率=(双倍)size.width/size.height;
如果(数学abs(比率-目标比率)>纵横比公差)继续;
if(数学绝对值(尺寸高度-目标值
/**
* A simple wrapper around a Camera and a SurfaceView that renders a centered preview of the Camera
* to the surface. We need to center the SurfaceView because not all devices have cameras that
* support preview sizes at the same aspect ratio as the device's display.
*/
public class Preview extends ViewGroup implements SurfaceHolder.Callback {
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Camera.Size mPreviewSize;
List<Camera.Size> mSupportedPreviewSizes;
Camera mCamera;
private Context context;
private int mCameraId;
public boolean use_front_camera;
public Preview(Context context, int cameraId) {
super(context);
this.context = context;
mCameraId = cameraId;
use_front_camera = true;
mSurfaceView = new SurfaceView(context);
addView(mSurfaceView);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
}
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
requestLayout();
}
}
public void switchCamera(Camera camera) {
setCamera(camera);
try {
camera.setPreviewDisplay(mHolder);
} catch (IOException exception) {
android.util.Log.e(IdelityConstants.DEBUG_IDELITY_KEY_LOG, "IOException caused by setPreviewDisplay()", exception);
}
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
camera.setParameters(parameters);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
//MUST CALL THIS
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed && getChildCount() > 0) {
final View child = getChildAt(0);
final int width = r - l;
final int height = b - t;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null) {
/**
* Como el calculo se hace con la cámara en modo landscape y luego toca
* girar la cámara para que se vea bien, se pasan los valores cambiados.
*/
previewWidth = mPreviewSize.height;
previewHeight = mPreviewSize.width;
}
// Center the child SurfaceView within the parent.
if (width * previewHeight < height * previewWidth) {
final int scaledChildWidth = previewWidth * height / previewHeight;
child.layout((width - scaledChildWidth) / 2, 0,
(width + scaledChildWidth) / 2, height);
} else {
final int scaledChildHeight = previewHeight * width / previewWidth;
child.layout(0, (height - scaledChildHeight) / 2,
width, (height + scaledChildHeight) / 2);
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(holder);
}
} catch (IOException exception) {
android.util.Log.e(IdelityConstants.DEBUG_IDELITY_KEY_LOG, "IOException caused by setPreviewDisplay()", exception);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// if (mCamera != null) {
// mCamera.stopPreview();
// }
}
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
if (mCamera == null)
return;
Camera.Parameters parameters = mCamera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
parameters.setJpegQuality(100);
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
Camera.Size size = sizes.get(0);
for(int i=0;i<sizes.size();i++)
{
if(sizes.get(i).width > size.width)
size = sizes.get(i);
}
parameters.setPictureSize(size.width, size.height);
requestLayout();
mCamera.setParameters(parameters);
mCamera.setDisplayOrientation(getCameraDisplayOrientation((FragmentActivity)context, mCameraId));
mCamera.startPreview();
}
public static int getCameraDisplayOrientation(FragmentActivity activity, int cameraId) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
}
else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
return result;
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(int cameraIndex){
Camera c = null;
try {
c = Camera.open(cameraIndex); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
android.util.Log.e(IdelityConstants.ERROR_IDELITY_KEY_LOG, "Camera is not available: " + e.getMessage());
}
return c; // returns null if camera is unavailable
}
}
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:id="@+id/capture_evidence_linearLayout_camera"
android:layout_weight="3"
android:layout_gravity="center_horizontal">
<FrameLayout
android:id="@+id/capture_evidence_camera_preview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/capture_evidence_default_text_number_evidence"
android:id="@+id/capture_evidence_textView_value_typed"
android:textSize="50sp"
android:textColor="@color/idelity_blanco"
android:gravity="center_horizontal"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:background="#d2000000"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:paddingTop="8dp"
android:paddingBottom="8dp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1">
<net.idelity.idelitymobile.ui.helpers.IdelityButton
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="@string/button_back"
android:id="@+id/capture_evidence_button_cancel"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="@drawable/button_gray"
android:textColor="@color/idelity_blanco"
android:textSize="20sp"
android:paddingLeft="40dp"
android:paddingRight="40dp"
android:textStyle="bold" />
<net.idelity.idelitymobile.ui.helpers.IdelityButton
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/capture_evidence_button_capture_evidence"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/capture_evidence_button_cancel"
android:layout_toEndOf="@+id/capture_evidence_button_cancel"
android:background="@drawable/take_photo_button_camera"
android:textSize="25sp"
android:textColor="@color/idelity_blanco"
android:textStyle="bold"
android:text="@string/capture_evidence_button_capture_evidence"
android:paddingBottom="10dp" />
</RelativeLayout>
//in getOptimalSize(int width, int height)
//isCameraOnSide() is a new method you should implement
//return true iff the camera is mounted on the side compared to
//the phone's natural orientation.
double targetRatio = (isCameraOnSide()) ? (double) height / width
: (double) width / height,
optimalRatio = 0.0,
acceptableRatioMargin = 0.1,
minDiff = Double.MAX_VALUE;
for(Camera.Size size : supportedSizes) {
optimalRatio = (double) size.width / size.height;
if(Math.abs(optimalRatio - targetRatio) < acceptableRatioMargin) {
if(Math.abs(height - size.height) < minDiff) {
minDiff = Math.abs(height - size.height);
optimalSize = size;
}
}
}
private boolean isCameraOnSide(){
int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
//Inquire the sensor's orientation relative to the natural phone's orientation
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(0, info); //Back-facing camera
int sensorOrientation = info.orientation;
boolean swappedDimensions = false;
switch (displayRotation) {
case Surface.ROTATION_0:
case Surface.ROTATION_180:
if (sensorOrientation == 90 || sensorOrientation == 270) {
swappedDimensions = true;
}
break;
case Surface.ROTATION_90:
case Surface.ROTATION_270:
if (sensorOrientation == 0 || sensorOrientation == 180) {
swappedDimensions = true;
}
break;
default:
Log.e(TAG, "Display rotation is invalid: " + displayRotation);
}
return swappedDimensions;
}
//inside surfaceCreated(SurfaceHolder holder)
Camera.Parameters params = mCamera.getParameters();
Camera.Size prevSize = getOptimalSize(getWidth(), getHeight());
//prevSize should be still in the camera's orientation. In your and my cases - landscape
params.setPreviewSize(prevSize.width, prevSize.height);
mCamera.setParameters(params);
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
public static Camera.Size determineBestPreviewSize(Camera.Parameters parameters) {
List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
return determineBestSize(sizes);
}
public static Camera.Size determineBestPictureSize(Camera.Parameters parameters) {
List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
return determineBestSize(sizes);
}
protected static Camera.Size determineBestSize(List<Camera.Size> sizes) {
Camera.Size bestSize = null;
long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long availableMemory = Runtime.getRuntime().maxMemory() - used;
for (Camera.Size currentSize : sizes) {
int newArea = currentSize.width * currentSize.height;
long neededMemory = newArea * 4 * 4; // newArea * 4 Bytes/pixel * 4 needed copies of the bitmap (for safety :) )
boolean isDesiredRatio = (currentSize.width / 4) == (currentSize.height / 3);
boolean isBetterSize = (bestSize == null || currentSize.width > bestSize.width);
boolean isSafe = neededMemory < availableMemory;
if (isDesiredRatio && isBetterSize && isSafe) {
bestSize = currentSize;
}
}
if (bestSize == null) {
return sizes.get(0);
}
return