android - camera2 捕捉与预览不同的图像
解决方案
这是AutoFitTextView
我从 Google 示例中提取的课程。你可以看看这里。它旨在显示相机视图并根据设备的物理尺寸配置比例。
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)
推荐阅读
- javascript - React API 错误(未处理的拒绝(TypeError):无法读取未定义的属性“0”)
- node.js - Node.js + Sequelize + SQL Server
- python - AttributeError:“numpy.float64”对象没有属性“值”
- c# - 为什么 typeA == typeB 比 typeA == typeof(TypeB) 慢?
- javascript - JavaScript:在 AWS Lambda 节点应用程序中将 RSS 转换为 JSON
- arduino - 使用操纵杆使伺服电机运动更顺畅?
- java - 处理来自 PostgreSQL 的大量数据
- javascript - NodeJS按时间戳显示文档有延迟
- jestjs - 再添加一个测试文件时,纱线测试挂起
- r - 使用带有多个参数和索引的 lapply/sapply 减少函数内的嵌套循环