答案 0 :(得分:2)
这是我从Google示例中提取的AutoFitTextView
类。您可以查看here。它旨在显示相机视图并根据设备的物理尺寸配置比例。
public class AutoFitTextureView extends TextureView {
private int mRatioWidth = 0;
private int mRatioHeight = 0;
// Some codes here...
public void setAspectRatio(int width, int height) {
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Size cannot be negative.");
}
mRatioWidth = width;
mRatioHeight = height;
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (0 == mRatioWidth || 0 == mRatioHeight) {
setMeasuredDimension(width, height);
} else {
if (width < height * mRatioWidth / mRatioHeight) {
setMeasuredDimension(width, width * mRatioHeight / mRatioWidth);
} else {
setMeasuredDimension(height * mRatioWidth / mRatioHeight, height);
}
}
}
}
本课程有2分:
if (width < height * mRatioWidth / mRatioHeight)
。应该为> ,因为当宽度大于高度时,我们将基于宽度(而非高度)计算并设置度量尺寸。已更新
如果只希望每个设备都可以特定的比率正常工作,则为其设置硬比率(例如:4/3)
您可以通过替换以下代码行来实现:
mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
maxPreviewHeight, largest);
-> previewSize = Size(4, 3)