在使用Android相机预览View时,有时我们需要对预览的图像进行裁剪以满足特定的需求,比如正方形裁剪或者只显示图像的某一部分。下面介绍一种通过自定义View实现预览裁剪的方法。
自定义一个继承自TextureView的类,比如名为CameraPreviewView的类。
在CameraPreviewView中重写onMeasure()方法,使其保持预览图像的比例。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (mAspectRatio != 0) {
if (width > height * mAspectRatio) {
width = (int) (height * mAspectRatio + 0.5);
} else {
height = (int) (width / mAspectRatio + 0.5);
}
}
setMeasuredDimension(width, height);
}
private Rect mClipRect = new Rect(0, 0, getWidth(), getHeight());
public void setClipRect(Rect rect) {
mClipRect = rect;
invalidate();
}
@Override
public void onDraw(Canvas canvas) {
// 裁剪画布
canvas.clipRect(mClipRect);
// 绘制预览图像
super.onDraw(canvas);
}
public void setCameraParams(Camera camera) {
Camera.Parameters params = camera.getParameters();
Camera.Size size = getOptimalPreviewSize(params.getSupportedPreviewSizes(), getWidth(), getHeight());
params.setPreviewSize(size.width, size.height);
camera.setParameters(params);
float aspectRatio = (float) size.width / size.height;
setAspectRatio(aspectRatio);
}
private Camera.Size getOptimalPreviewSize(List sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h