// Import necessary packages
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
// Define class that implements SurfaceHolder.Callback
public class CustomCamera implements SurfaceHolder.Callback {
// Declare variables
private Camera mCamera;
private SurfaceHolder mHolder;
// Constructor
public CustomCamera(SurfaceView surfaceView) {
// Get SurfaceHolder from SurfaceView
mHolder = surfaceView.getHolder();
// Set this class as the callback for SurfaceHolder events
mHolder.addCallback(this);
}
// Implement SurfaceHolder.Callback methods
@Override
public void surfaceCreated(SurfaceHolder holder) {
// Open camera and set preview display
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Set camera parameters for preview size and aspect ratio
Camera.Parameters parameters = mCamera.getParameters();
Camera.Size previewSize = getOptimalPreviewSize(parameters.getSupportedPreviewSizes(), 4, 3);
parameters.setPreviewSize(previewSize.width, previewSize.height);
mCamera.setParameters(parameters);
mCamera.startPreview();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Release camera resources
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
// Define method to get optimal preview size based on aspect ratio
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int width, int height) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) width / height;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = height;
// Try to find a size that matches the target aspect ratio and has the closest height
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// If no size matches the target aspect ratio, choose the one with the closest aspect ratio
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) < minDiff) {
optimalSize = size;
minDiff = Math.abs(ratio - targetRatio);
}
}
}
return optimalSize;
}
}
// To get a 4:3 aspect ratio, we need to find the optimal preview size with a width-to-height ratio of 4:3.
// We can do this by iterating through the list of supported preview sizes and finding the one with the closest height to the target height (which is 3/4 of the target width).
// If there is no size with a 4:3 aspect ratio, we choose the one with the closest aspect ratio.
// We then set the camera parameters to use this preview size.
网友评论