Результатом работы сценария использования CameraX являются два компонента: буфер и информация о преобразовании. Буфер представляет собой массив байтов, а информация о преобразовании определяет, как буфер должен быть обрезан и повернут перед отображением конечным пользователям. Способ применения преобразования зависит от формата буфера.
ImageCapture
В случае использования ImageCapture буфер прямоугольника обрезки применяется перед сохранением на диск, а поворот сохраняется в данных Exif. Никаких дополнительных действий от приложения не требуется.
Предварительный просмотр
В Preview версии вы можете получить информацию о преобразовании, вызвав SurfaceRequest.setTransformationInfoListener() . Каждый раз, когда преобразование обновляется, вызывающая сторона получает новый объект SurfaceRequest.TransformationInfo .
Способ применения информации о преобразовании зависит от источника Surface и обычно нетривиален. Если цель состоит в простом отображении предварительного просмотра, используйте PreviewView . PreviewView — это настраиваемое представление, которое автоматически обрабатывает преобразование. Для более сложных случаев, когда вам нужно редактировать поток предварительного просмотра, например, с помощью OpenGL, обратитесь к примеру кода в тестовом приложении CameraX core .
Преобразовать координаты
Ещё одна распространённая задача — работа с координатами вместо буфера, например, обводка рамкой обнаруженного лица в режиме предварительного просмотра. В таких случаях необходимо преобразовать координаты обнаруженного лица из данных анализа изображения в данные предварительного просмотра.
Приведенный ниже фрагмент кода создает матрицу, которая сопоставляет координаты анализа изображения с координатами PreviewView . Для преобразования координат (x, y) с помощью Matrix см. Matrix.mapPoints() .
Котлин
fun getCorrectionMatrix(imageProxy: ImageProxy, previewView: PreviewView) : Matrix { val cropRect = imageProxy.cropRect val rotationDegrees = imageProxy.imageInfo.rotationDegrees val matrix = Matrix() // A float array of the source vertices (crop rect) in clockwise order. val source = floatArrayOf( cropRect.left.toFloat(), cropRect.top.toFloat(), cropRect.right.toFloat(), cropRect.top.toFloat(), cropRect.right.toFloat(), cropRect.bottom.toFloat(), cropRect.left.toFloat(), cropRect.bottom.toFloat() ) // A float array of the destination vertices in clockwise order. val destination = floatArrayOf( 0f, 0f, previewView.width.toFloat(), 0f, previewView.width.toFloat(), previewView.height.toFloat(), 0f, previewView.height.toFloat() ) // The destination vertexes need to be shifted based on rotation degrees. The // rotation degree represents the clockwise rotation needed to correct the image. // Each vertex is represented by 2 float numbers in the vertices array. val vertexSize = 2 // The destination needs to be shifted 1 vertex for every 90° rotation. val shiftOffset = rotationDegrees / 90 * vertexSize; val tempArray = destination.clone() for (toIndex in source.indices) { val fromIndex = (toIndex + shiftOffset) % source.size destination[toIndex] = tempArray[fromIndex] } matrix.setPolyToPoly(source, 0, destination, 0, 4) return matrix }
Java
Matrix getMappingMatrix(ImageProxy imageProxy, PreviewView previewView) { Rect cropRect = imageProxy.getCropRect(); int rotationDegrees = imageProxy.getImageInfo().getRotationDegrees(); Matrix matrix = new Matrix(); // A float array of the source vertices (crop rect) in clockwise order. float[] source = { cropRect.left, cropRect.top, cropRect.right, cropRect.top, cropRect.right, cropRect.bottom, cropRect.left, cropRect.bottom }; // A float array of the destination vertices in clockwise order. float[] destination = { 0f, 0f, previewView.getWidth(), 0f, previewView.getWidth(), previewView.getHeight(), 0f, previewView.getHeight() }; // The destination vertexes need to be shifted based on rotation degrees. // The rotation degree represents the clockwise rotation needed to correct // the image. // Each vertex is represented by 2 float numbers in the vertices array. int vertexSize = 2; // The destination needs to be shifted 1 vertex for every 90° rotation. int shiftOffset = rotationDegrees / 90 * vertexSize; float[] tempArray = destination.clone(); for (int toIndex = 0; toIndex < source.length; toIndex++) { int fromIndex = (toIndex + shiftOffset) % source.length; destination[toIndex] = tempArray[fromIndex]; } matrix.setPolyToPoly(source, 0, destination, 0, 4); return matrix; }