Returns a Size object containing the dimensions for an optimal preview size for the current hardware - Android android.hardware

Android examples for android.hardware:Camera Preview

Description

Returns a Size object containing the dimensions for an optimal preview size for the current hardware

Demo Code

import java.util.List;

import android.hardware.Camera.Size;

public class Main {

  /**//  w  w  w .j  a va  2  s .c  o m
   * Returns a Size object containing the dimensions for an optimal preview size
   * for the current hardware. This code is based on that found at:
   * http://developer.android.com/resources/samples/ApiDemos/src/com/example/
   * android/apis/graphics/CameraPreview.html
   * 
   * @param supportedSizes
   *          A list of Size objects representing all the known preview sizes
   *          supported by this hardware.
   * 
   * @param w
   *          The surface width.
   * 
   * @param h
   *          The surface height.
   * 
   * @return Returns a Size object containing the dimensions for an optimal
   *         preview size for the current hardware.
   */
  public static Size getOptimalPreviewSize(List<Size> supportedSizes, int w, int h) {
    final double ASPECT_TOLERANCE = 0.05;
    double targetRatio = (double) w / h;
    if (supportedSizes == null)
      return null;

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

    int targetHeight = h;

    // Try to find an size match aspect ratio and size
    for (Size size : supportedSizes) {
      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 (Size size : supportedSizes) {
        if (Math.abs(size.height - targetHeight) < minDiff) {
          optimalSize = size;
          minDiff = Math.abs(size.height - targetHeight);
        }
      }
    }
    return optimalSize;
  }

}

Related Tutorials