find Closet Preview Size - Android android.hardware

Android examples for android.hardware:Camera Preview

Description

find Closet Preview Size

Demo Code

import java.util.List;

import android.graphics.Point;
import android.hardware.Camera;
import android.util.Log;

public class Main {

  private static final String TAG = "Camera";

  public static Camera.Size findClosetPreviewSize(Camera camera, Point preferSize) {
    int preferX = preferSize.x;
    int preferY = preferSize.y;
    Camera.Parameters parameters = camera.getParameters();
    List<Camera.Size> allSupportSizes = parameters.getSupportedPreviewSizes();
    Log.d(TAG, "all support preview size: " + dumpPreviewSizeList(allSupportSizes));
    int minDiff = Integer.MAX_VALUE;
    int index = 0;
    for (int i = 0; i < allSupportSizes.size(); i++) {
      Camera.Size size = allSupportSizes.get(i);
      int x = size.width;
      int y = size.height;

      int diff = Math.abs(x - preferX) + Math.abs(y - preferY);
      if (diff < minDiff) {
        minDiff = diff;/*from  w  w w .j a va 2  s . com*/
        index = i;
      }
    }

    Camera.Size size = allSupportSizes.get(index);
    return size;
  }

  private static String dumpPreviewSizeList(List<Camera.Size> sizes) {
    String result = "";
    for (Camera.Size size : sizes) {
      result += "(" + size.width + "," + size.height + ") ";
    }
    return result;
  }

}

Related Tutorials