From 7ac6f4d008af15e16c55e8bb23998e676c7fb931 Mon Sep 17 00:00:00 2001 From: Marc Rousavy Date: Mon, 19 Feb 2024 14:54:13 +0100 Subject: [PATCH] fix: Trigger `measure` and `layout` manually in PreviewView (#2588) * fix: Trigger `measure` and `layout` manually to fix Preview stretching * fix: Check for `0`/`NaN` --- .../java/com/mrousavy/camera/core/PreviewView.kt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/package/android/src/main/java/com/mrousavy/camera/core/PreviewView.kt b/package/android/src/main/java/com/mrousavy/camera/core/PreviewView.kt index ba3c94b..0727a1f 100644 --- a/package/android/src/main/java/com/mrousavy/camera/core/PreviewView.kt +++ b/package/android/src/main/java/com/mrousavy/camera/core/PreviewView.kt @@ -90,9 +90,23 @@ class PreviewView(context: Context, callback: SurfaceHolder.Callback) : } } + override fun requestLayout() { + super.requestLayout() + // Manually trigger measure & layout, as RN on Android skips those. + // See this issue: https://github.com/facebook/react-native/issues/17968#issuecomment-721958427 + post { + measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)) + layout(left, top, right, bottom) + } + } + private fun getSize(contentSize: Size, containerSize: Size, resizeMode: ResizeMode): Size { val contentAspectRatio = contentSize.width.toDouble() / contentSize.height val containerAspectRatio = containerSize.width.toDouble() / containerSize.height + if (!(contentAspectRatio > 0 && containerAspectRatio > 0)) { + // One of the aspect ratios is 0 or NaN, maybe the view hasn't been laid out yet. + return contentSize + } val widthOverHeight = when (resizeMode) { ResizeMode.COVER -> contentAspectRatio > containerAspectRatio