Search code examples
androidkotlinandroid-camera2textureview

Rotating camera stream with TextureView crops the image


The camera in the device that I am using returns rotated image (landscape 16:9). In order to acquire stream I use Camera2 API and for projection I use TextureView. TextureView is fixed size. When I try to rotate it using Matrixit results in cropped image.

Here is what I have before the rotation:

enter image description here

Then I rotate it and adjust TextureView size like that:

private fun updateTransform() {
    val matrix = Matrix()
    val centerX = textureView.width / 2f
    val centerY = textureView.height / 2f
    matrix.postRotate(90.toFloat(), centerX, centerY)
    textureView.setTransform(matrix)
    textureView.layoutParams = FrameLayout.LayoutParams(textureView.width, textureView.height)
}

That results in the following image:

enter image description here

I'd like the image to be stretched to fill TextureView. Important to note is that I don't need to consider device rotation because it's always portrait. I am also programming for one device only so I don't need to consider different camera types etc.

How can I rotate the image without cropping it?


Solution

  • This transformation fixed my problem:

        private fun transformTexture() {
        val adjustment = Matrix()
        val centerX = textureView.width / 2f
        val centerY = textureView.height / 2f
    
        val scalex = textureView.width.toFloat() / textureView.height.toFloat()
        val scaley = textureView.height.toFloat() / textureView.width.toFloat()
    
        adjustment.postRotate(90F, centerX, centerY)
        adjustment.postScale(scalex, scaley, centerX, centerY)
    
        textureView.setTransform(adjustment)
    }