protected Matrix calculateTextureTransform(Size textureSize, Size previewSize) {
        float ratioTexture = (float) textureSize.width / (float) textureSize.height;
        float ratioPreview = (float) previewSize.width / (float) previewSize.height;

        float scaleX;
        float scaleY;

        // We scale so that either width or height fits exactly in the TextureView, and the other
        // is bigger (cropped).
        if (ratioTexture < ratioPreview) {
            scaleX = ratioPreview / ratioTexture;
            scaleY = 1;
        } else {
            scaleX = 1;
            scaleY = ratioTexture / ratioPreview;
        }

        Matrix matrix = new Matrix();

        matrix.setScale(scaleX, scaleY);

        // Center the preview
        float scaledWidth = textureSize.width * scaleX;
        float scaledHeight = textureSize.height * scaleY;
        float dx = (textureSize.width - scaledWidth) / 2;
        float dy = (textureSize.height - scaledHeight) / 2;

        // Perform the translation on the scaled preview
        matrix.postTranslate(dx, dy);

        return matrix;
    }
Calculate transformation for the TextureView.

An identity matrix would cause the preview to be scaled up/down to fill the TextureView.

@param textureSize the size of the textureView
@param previewSize the camera preview resolution
@return the transform matrix for the TextureView
zxing-android-embedded/src/com/journeyapps/barcodescanner/CameraPreview.java