固定尺寸SurfaceView - Android

时间:2015-10-29 18:44:14

标签: android camera surfaceview preview aspect-ratio

我正在尝试使用SurfaceView以纵向模式预览相机。我正在初始化相机,一切正常。 但是,我的SurfaceView有一个固定的大小,如下所示:

<SurfaceView android:id="@+id/surface_view"
                    android:layout_width="match_parent"
                    android:layout_height="250dp" />

我无法以正确的比例预览,预览总是拉伸。

我正在使用以下方法计算预览相机分辨率:

private Point findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution, Rect surfaceFrame) {

// Sort by size, descending
List<Camera.Size> supportedPreviewSizes = new ArrayList<Camera.Size>(parameters.getSupportedPreviewSizes());
Collections.sort(supportedPreviewSizes, new Comparator<Camera.Size>() {
  @Override
  public int compare(Camera.Size a, Camera.Size b) {
    int aPixels = a.height * a.width;
    int bPixels = b.height * b.width;
    if (bPixels < aPixels) {
      return -1;
    }
    if (bPixels > aPixels) {
      return 1;
    }
    return 0;
  }
});

int w;
int h;

if(surfaceFrame == null) {
  w = screenResolution.x;
  h = screenResolution.y;
} else {
  w = surfaceFrame.width();
  h = surfaceFrame.height();
}

Log.i(TAG, "Surface resolution is " + new Point(w, h));

final double ASPECT_TOLERANCE = 0.1;
double targetRatio=(double)h / w;

if (supportedPreviewSizes == null) return null;

Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;

int targetHeight = h;

for (Camera.Size size : supportedPreviewSizes) {
  double ratio = (double) size.height / size.width;
  if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
  if (Math.abs(size.height - targetHeight) < minDiff) {
    optimalSize = size;
    minDiff = Math.abs(size.height - targetHeight);
  }
}

if (optimalSize == null) {
  minDiff = Double.MAX_VALUE;
  for (Camera.Size size : supportedPreviewSizes) {
    if (Math.abs(size.height - targetHeight) < minDiff) {
      optimalSize = size;
      minDiff = Math.abs(size.height - targetHeight);
    }
  }
}

Point p = new Point(optimalSize.width, optimalSize.height);
Log.i(TAG, "Camera resolution is "+ p.toString());
return p;}

有没有办法在不修改SurfaceView尺寸的情况下以正确的宽高比显示相机预览?

提前致谢

0 个答案:

没有答案