下面列出了怎么用android.util.Size的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* {@inheritDoc}
*/
@Override
public int compare(Size size, Size size2) {
checkNotNull(size, "size must not be null");
checkNotNull(size2, "size2 must not be null");
if (size.equals(size2)) {
return 0;
}
long width = size.getWidth();
long width2 = size2.getWidth();
long area = width * size.getHeight();
long area2 = width2 * size2.getHeight();
if (area == area2) {
return (width > width2) ? 1 : -1;
}
return (area > area2) ? 1 : -1;
}
/**
* Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
* width and height are at least as large as the respective requested values, and whose aspect
* ratio matches with the specified value.
*
* @param choices The list of sizes that the camera supports for the intended output class
* @param width The minimum desired width
* @param height The minimum desired height
* @param aspectRatio The aspect ratio
* @return The optimal {@code Size}, or an arbitrary one if none were big enough
*/
private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
// Collect the supported resolutions that are at least as big as the preview Surface
List<Size> bigEnough = new ArrayList<Size>();
int w = aspectRatio.getWidth();
int h = aspectRatio.getHeight();
for (Size option : choices) {
if (option.getHeight() == option.getWidth() * h / w &&
option.getWidth() >= width && option.getHeight() >= height) {
bigEnough.add(option);
}
}
// Pick the smallest of those, assuming we found any
if (bigEnough.size() > 0) {
return Collections.min(bigEnough, new CompareSizesByArea());
} else {
Log.e(TAG, "Couldn't find any suitable preview size");
return choices[0];
}
}
/**
* Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
* width and height are at least as large as the minimum of both, or an exact match if possible.
*
* @param choices The list of sizes that the camera supports for the intended output class
* @return The optimal {@code Size}, or an arbitrary one if none were big enough
*/
private static Size chooseOptimalSize(final Size[] choices) {
final int minSize = Math.max(Math.min(DESIRED_PREVIEW_SIZE.getWidth(),
DESIRED_PREVIEW_SIZE.getHeight()), MINIMUM_PREVIEW_SIZE);
// Collect the supported resolutions that are at least as big as the preview Surface
final List<Size> bigEnough = new ArrayList();
for (final Size option : choices) {
if (option.equals(DESIRED_PREVIEW_SIZE)) {
return DESIRED_PREVIEW_SIZE;
}
if (option.getHeight() >= minSize && option.getWidth() >= minSize) {
bigEnough.add(option);
}
}
// Pick the smallest of those, assuming we found any
return (bigEnough.size() > 0) ? Collections.min(bigEnough, new CompareSizesByArea()) : choices[0];
}
/**
* カメラがサポートしているプレビューサイズから指定のサイズに近い値を返却します.
*
* @param width 横幅
* @param height 縦幅
* @return 近い値
*/
public Size getApproximatePreviewSize(final int width, final int height) {
List<Size> sizes = getSupportedPreviewSizes();
if (sizes.isEmpty()) {
return null;
}
Size currentSize = sizes.get(0);
int value = Integer.MAX_VALUE;
for (Size size : sizes) {
int dw = width - size.getWidth();
int dh = height - size.getHeight();
int dist = dw * dw + dh * dh;
if (dist < value) {
currentSize = size;
value = dist;
}
}
return currentSize;
}
@SuppressWarnings("unchecked")
private void layoutOverflowPanelItems(List<MenuItem> menuItems) {
ArrayAdapter<MenuItem> overflowPanelAdapter = (ArrayAdapter<MenuItem>) mOverflowPanel.getAdapter();
overflowPanelAdapter.clear();
final int size = menuItems.size();
for (int i = 0; i < size; i++) {
overflowPanelAdapter.add(menuItems.get(i));
}
mOverflowPanel.setAdapter(overflowPanelAdapter);
if (mOpenOverflowUpwards) {
mOverflowPanel.setY(0);
} else {
mOverflowPanel.setY(mOverflowButtonSize.getHeight());
}
int width = Math.max(getOverflowWidth(), mOverflowButtonSize.getWidth());
int height = calculateOverflowHeight(MAX_OVERFLOW_SIZE);
mOverflowPanelSize = new Size(width, height);
setSize(mOverflowPanel, mOverflowPanelSize);
}
/**
* カメラデバイスの設定を初期化します.
*/
private void initSettings() {
try {
String cameraId = Camera2Helper.getCameraId(mCameraManager, CameraCharacteristics.LENS_FACING_BACK);
if (cameraId == null) {
cameraId = Camera2Helper.getCameraId(mCameraManager, CameraCharacteristics.LENS_FACING_FRONT);
}
mSettings.setCameraId(cameraId);
} catch (Exception e) {
throw new RuntimeException("Not support.");
}
List<Size> pictureSizes = mSettings.getSupportedPictureSizes();
if (!pictureSizes.isEmpty()) {
mSettings.setPictureSize(pictureSizes.get(0));
}
List<Size> previewSizes = mSettings.getSupportedPreviewSizes();
if (!previewSizes.isEmpty()) {
mSettings.setPreviewSize(previewSizes.get(previewSizes.size() - 2));
}
}
@Override
protected List<PreviewSize> getSupportedSize() {
try {
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(
getCurrentCameraId());
StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
return Collections.singletonList(new PreviewSize(mPreviewWidth, mPreviewHeight));
}
Size[] supportedSize = map.getOutputSizes(SurfaceTexture.class);
if (supportedSize == null || supportedSize.length == 0) {
return Collections.singletonList(new PreviewSize(mPreviewWidth, mPreviewHeight));
}
List<PreviewSize> results = new ArrayList<>();
for (Size size : supportedSize) {
results.add(new PreviewSize(size.getWidth(), size.getHeight()));
}
return results;
} catch (CameraAccessException e) {
throw new CameraAccessError();
}
}
/**
* カメラID に対応したカメラデバイスがサポートしているプレビューサイズのリストを取得します.
*
* @param cameraManager カメラマネージャ
* @param cameraId カメラID
* @return サポートしているプレビューサイズのリスト
*/
@NonNull
private static List<Size> getSupportedPreviewSizes(final CameraManager cameraManager, final String cameraId) {
List<Size> previewSizes = new ArrayList<>();
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map != null) {
previewSizes = Arrays.asList(map.getOutputSizes(SurfaceTexture.class));
Collections.sort(previewSizes, SIZE_COMPARATOR);
}
} catch (CameraAccessException e) {
// ignore.
}
return previewSizes;
}
public Size[] getCameraResolutions(Facing facing) {
try {
CameraCharacteristics characteristics = getCharacteristicsForFacing(cameraManager, facing);
if (characteristics == null) {
return new Size[0];
}
StreamConfigurationMap streamConfigurationMap =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Size[] outputSizes = streamConfigurationMap.getOutputSizes(SurfaceTexture.class);
return outputSizes != null ? outputSizes : new Size[0];
} catch (CameraAccessException | NullPointerException e) {
Log.e(TAG, "Error", e);
return new Size[0];
}
}
/**
* Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
* width and height are at least as large as the respective requested values, and whose aspect
* ratio matches with the specified value.
*
* @param choices The list of sizes that the camera supports for the intended output class
* @param width The minimum desired width
* @param height The minimum desired height
* @param aspectRatio The aspect ratio
* @return The optimal {@code Size}, or an arbitrary one if none were big enough
*/
@SuppressLint("LongLogTag")
@DebugLog
private static Size chooseOptimalSize(
final Size[] choices, final int width, final int height, final Size aspectRatio) {
// Collect the supported resolutions that are at least as big as the preview Surface
final List<Size> bigEnough = new ArrayList<Size>();
for (final Size option : choices) {
if (option.getHeight() >= MINIMUM_PREVIEW_SIZE && option.getWidth() >= MINIMUM_PREVIEW_SIZE) {
Log.i(TAG, "Adding size: " + option.getWidth() + "x" + option.getHeight());
bigEnough.add(option);
} else {
Log.i(TAG, "Not adding size: " + option.getWidth() + "x" + option.getHeight());
}
}
// Pick the smallest of those, assuming we found any
if (bigEnough.size() > 0) {
final Size chosenSize = Collections.min(bigEnough, new CompareSizesByArea());
Log.i(TAG, "Chosen size: " + chosenSize.getWidth() + "x" + chosenSize.getHeight());
return chosenSize;
} else {
Log.e(TAG, "Couldn't find any suitable preview size");
return choices[0];
}
}
protected void setFragment() {
cameraId = chooseCamera();
final CameraConnectionFragment fragment =
CameraConnectionFragment.newInstance(
new CameraConnectionFragment.ConnectionCallback() {
@Override
public void onPreviewSizeChosen(final Size previewSize, final Size cameraViewSize, final int rotation) {
BaseCameraActivity.this.onPreviewSizeChosen(previewSize, cameraViewSize, rotation);
}
},
this,
getLayoutId(),
getDesiredPreviewFrameSize());
fragment.setCamera(cameraId);
getFragmentManager()
.beginTransaction()
.replace(R.id.camera_container, fragment)
.commit();
}
/**
* Configures the necessary {@link Matrix} transformation to `mTextureView`.
* This method should be called after the camera preview size is determined in
* setUpCameraOutputs and also the size of `mTextureView` is fixed.
*
* @param viewWidth The width of `mTextureView`
* @param viewHeight The height of `mTextureView`
*/
private void configureTransform(final int viewWidth, final int viewHeight) {
Size previewSize = mSettings.getPreviewSize();
int rotation = Camera2Helper.getDisplayRotation(mContext);
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, previewSize.getHeight(), previewSize.getWidth());
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.max(
(float) viewHeight / previewSize.getHeight(),
(float) viewWidth / previewSize.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
} else if (Surface.ROTATION_180 == rotation) {
matrix.postRotate(180, centerX, centerY);
}
mTextureView.setTransform(matrix);
}
private void appendOutputsString(StringBuilder sb) {
sb.append("Outputs(");
int[] formats = getOutputFormats();
for (int format : formats) {
Size[] sizes = getOutputSizes(format);
for (Size size : sizes) {
long minFrameDuration = getOutputMinFrameDuration(format, size);
long stallDuration = getOutputStallDuration(format, size);
sb.append(String.format("[w:%d, h:%d, format:%s(%d), min_duration:%d, " +
"stall:%d], ", size.getWidth(), size.getHeight(), formatToString(format),
format, minFrameDuration, stallDuration));
}
}
// Remove the pending ", "
if (sb.charAt(sb.length() - 1) == ' ') {
sb.delete(sb.length() - 2, sb.length());
}
sb.append(")");
}
protected void setFragment() {
cameraId = chooseCamera();
final CameraConnectionFragment fragment =
CameraConnectionFragment.newInstance(
new CameraConnectionFragment.ConnectionCallback() {
@Override
public void onPreviewSizeChosen(final Size previewSize, final Size cameraViewSize, final int rotation) {
BaseCameraActivity.this.onPreviewSizeChosen(previewSize, cameraViewSize, rotation);
}
},
this,
getLayoutId(),
getDesiredPreviewFrameSize());
fragment.setCamera(cameraId);
getFragmentManager()
.beginTransaction()
.replace(R.id.camera_container, fragment)
.commit();
}
/**
* Create a new {@link HighSpeedVideoConfiguration}.
*
* @param width image width, in pixels (positive)
* @param height image height, in pixels (positive)
* @param fpsMin minimum frames per second for the configuration (positive)
* @param fpsMax maximum frames per second for the configuration (larger or equal to 60)
*
* @throws IllegalArgumentException
* if width/height/fpsMin were not positive or fpsMax less than 60
*
* @hide
*/
public HighSpeedVideoConfiguration(
final int width, final int height, final int fpsMin, final int fpsMax,
final int batchSizeMax) {
if (fpsMax < HIGH_SPEED_MAX_MINIMAL_FPS) {
throw new IllegalArgumentException("fpsMax must be at least " +
HIGH_SPEED_MAX_MINIMAL_FPS);
}
mFpsMax = fpsMax;
mWidth = checkArgumentPositive(width, "width must be positive");
mHeight = checkArgumentPositive(height, "height must be positive");
mFpsMin = checkArgumentPositive(fpsMin, "fpsMin must be positive");
mSize = new Size(mWidth, mHeight);
mBatchSizeMax = checkArgumentPositive(batchSizeMax, "batchSizeMax must be positive");
mFpsRange = new Range<Integer>(mFpsMin, mFpsMax);
}
public static ImageTransferFormatSelectorDialogFragment newInstance(boolean isEInkModeEnabled, Size resolution) {
ImageTransferFormatSelectorDialogFragment fragment = new ImageTransferFormatSelectorDialogFragment();
Bundle args = new Bundle();
args.putBoolean(ARG_PARAM_ISEINKMODEENABLED, isEInkModeEnabled);
args.putInt(ARG_PARAM_RESOLUTION_WIDTH, resolution.getWidth());
args.putInt(ARG_PARAM_RESOLUTION_HEIGHT, resolution.getHeight());
fragment.setArguments(args);
return fragment;
}
protected Size calculateViewSize(int width, int height, Size maxSize) {
int h = maxSize.getWidth() * height / width;
if (h % 2 != 0) {
h--;
}
if (maxSize.getHeight() < h) {
int w = maxSize.getHeight() * width / height;
if (w % 2 != 0) {
w--;
}
return new Size(w, maxSize.getHeight());
}
return new Size(maxSize.getWidth(), h);
}
private Size chooseOptimalSize(Size[] sizes, int viewWidth, int viewHeight, Size pictureSize) {
int totalRotation = getRotation();
boolean swapRotation = totalRotation == 90 || totalRotation == 270;
int width = swapRotation ? viewHeight : viewWidth;
int height = swapRotation ? viewWidth : viewHeight;
return getSuitableSize(sizes, width, height, pictureSize);
}
public static CameraConnectionFragment newInstance(
final ConnectionCallback callback,
final OnImageAvailableListener imageListener,
final int layout,
final Size inputSize) {
return new CameraConnectionFragment(callback, imageListener, layout, inputSize);
}
@NonNull
private static MediaFormat createVideoOutputFormatWithAvailableEncoders(@NonNull final VideoFormatMimeType mimeType,
final int bitrate,
@NonNull final Size outputResolution) {
final MediaCodecList mediaCodecList = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
if (mimeType != VideoFormatMimeType.AUTO) {
final MediaFormat mediaFormat = createVideoFormat(mimeType.getFormat(), bitrate, outputResolution);
if (mediaCodecList.findEncoderForFormat(mediaFormat) != null) {
return mediaFormat;
}
}
final MediaFormat hevcMediaFormat = createVideoFormat(VideoFormatMimeType.HEVC.getFormat(), bitrate, outputResolution);
if (mediaCodecList.findEncoderForFormat(hevcMediaFormat) != null) {
return hevcMediaFormat;
}
final MediaFormat avcMediaFormat = createVideoFormat(VideoFormatMimeType.AVC.getFormat(), bitrate, outputResolution);
if (mediaCodecList.findEncoderForFormat(avcMediaFormat) != null) {
return avcMediaFormat;
}
final MediaFormat mp4vesMediaFormat = createVideoFormat(VideoFormatMimeType.MPEG4.getFormat(), bitrate, outputResolution);
if (mediaCodecList.findEncoderForFormat(mp4vesMediaFormat) != null) {
return mp4vesMediaFormat;
}
return createVideoFormat(VideoFormatMimeType.H263.getFormat(), bitrate, outputResolution);
}
/**
* In this sample, we choose a video size with 3x4 aspect ratio. Also, we don't use sizes
* larger than 1080p, since MediaRecorder cannot handle such a high-resolution video.
*
* @param choices The list of available sizes
* @return The video size
*/
private static Size chooseVideoSize(Size[] choices) {
for (Size size : choices) {
if (size.getWidth() == 1280 && size.getHeight() <= 720) {
return size;
}
}
Log.e(TAG, "Couldn't find any suitable video size");
return choices[choices.length - 1];
}
public synchronized CameraApi configCamera() {
if (mCamera == null) {
if (cameraApiCallback != null)
cameraApiCallback.onNotSupportErrorTip(context.getString(R.string.init_camera_error));
return this;
}
mCameraParameters = mCamera.getParameters();
List<Integer> supportFormat = mCameraParameters.getSupportedPreviewFormats();
for (Integer f : supportFormat
) {
Log.e(TAG, "configCamera: f = " + f + "--");
}
List<Camera.Size> supportedPreviewSizes = mCameraParameters.getSupportedPreviewSizes();
if (!isPreviewSizeSupport(supportedPreviewSizes)) {
mPreviewWidth = DEFAULT_PREVIEW_WIDTH;
mPreviewHeight = DEFAULT_PREVIEW_HEIGHT;
}
mCameraParameters.setPreviewFormat(ImageFormat.NV21);
mCameraParameters.setPreviewSize(mPreviewWidth, mPreviewHeight);
setCameraFps(mCameraParameters, fps);
mCamera.setParameters(mCameraParameters);
setupOrientaition(context);
for (int i = 0; i < BUFFER_COUNT; i++) {
mCamera.addCallbackBuffer(new byte[mPreviewHeight * mPreviewWidth * 3 / 2]);
}
return this;
}
public static CameraConnectionFragment newInstance(
final ConnectionCallback callback,
final OnImageAvailableListener imageListener,
final int layout,
final Size inputSize,
CameraOpenListener openListener) {
return new CameraConnectionFragment(callback, imageListener, layout, inputSize, openListener);
}
static Size getBestCameraSize(Size[] availableCameraResolutions, Size minSize) {
// This should select the closest size that is not too small
Arrays.sort(availableCameraResolutions, new CompareSizesByArea()); // Sort by smallest first
for (Size resolution : availableCameraResolutions) {
if (resolution.getWidth() >= minSize.getWidth() &&
resolution.getHeight() >= minSize.getHeight()) {
return resolution;
}
}
return null;
}
private CameraConnectionFragment(
final ConnectionCallback connectionCallback,
final OnImageAvailableListener imageListener,
final int layout,
final Size inputSize) {
this.cameraConnectionCallback = connectionCallback;
this.imageListener = imageListener;
this.layout = layout;
this.inputSize = inputSize;
}
@Override
public int compare(Size lhs, Size rhs) {
Log.d(TAG, "compare: ");
// We cast here to ensure the multiplications won't overflow
return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
(long) rhs.getWidth() * rhs.getHeight());
}
private boolean isWithinBounds(Context context, MasterSecret masterSecret, Uri uri) throws IOException {
try {
InputStream is = PartAuthority.getAttachmentStream(context, masterSecret, uri);
Size size = BitmapUtils.INSTANCE.getImageDimensions(is);
return size.getWidth() > 0 && size.getWidth() <= getImageMaxWidth(context) &&
size.getHeight() > 0 && size.getHeight() <= getImageMaxHeight(context);
} catch (Exception e) {
throw new IOException(e);
}
}
public static WmDisplayCutout computeSafeInsets(DisplayCutout inner,
int displayWidth, int displayHeight) {
if (inner == DisplayCutout.NO_CUTOUT || inner.isBoundsEmpty()) {
return NO_CUTOUT;
}
final Size displaySize = new Size(displayWidth, displayHeight);
final Rect safeInsets = computeSafeInsets(displaySize, inner);
return new WmDisplayCutout(inner.replaceSafeInsets(safeInsets), displaySize);
}
private CameraConnectionFragment(
final ConnectionCallback connectionCallback,
final OnImageAvailableListener imageListener,
final int layout,
final Size inputSize) {
this.cameraConnectionCallback = connectionCallback;
this.imageListener = imageListener;
this.layout = layout;
this.inputSize = inputSize;
}
/**
* Create an OutputConfiguration from Parcel.
*/
private OutputConfiguration(@NonNull Parcel source) {
int rotation = source.readInt();
int surfaceSetId = source.readInt();
int surfaceType = source.readInt();
int width = source.readInt();
int height = source.readInt();
boolean isDeferred = source.readInt() == 1;
boolean isShared = source.readInt() == 1;
ArrayList<Surface> surfaces = new ArrayList<Surface>();
source.readTypedList(surfaces, Surface.CREATOR);
String physicalCameraId = source.readString();
checkArgumentInRange(rotation, ROTATION_0, ROTATION_270, "Rotation constant");
mSurfaceGroupId = surfaceSetId;
mRotation = rotation;
mSurfaces = surfaces;
mConfiguredSize = new Size(width, height);
mIsDeferredConfig = isDeferred;
mIsShared = isShared;
mSurfaces = surfaces;
if (mSurfaces.size() > 0) {
mSurfaceType = SURFACE_TYPE_UNKNOWN;
mConfiguredFormat = SurfaceUtils.getSurfaceFormat(mSurfaces.get(0));
mConfiguredDataspace = SurfaceUtils.getSurfaceDataspace(mSurfaces.get(0));
mConfiguredGenerationId = mSurfaces.get(0).getGenerationId();
} else {
mSurfaceType = surfaceType;
mConfiguredFormat = StreamConfigurationMap.imageFormatToInternal(ImageFormat.PRIVATE);
mConfiguredDataspace =
StreamConfigurationMap.imageFormatToDataspace(ImageFormat.PRIVATE);
mConfiguredGenerationId = 0;
}
mPhysicalCameraId = physicalCameraId;
}