remove PreviewView onMeasure override and let SurfaceView setup the correct size

This commit is contained in:
Rui Rodrigues 2024-08-21 16:26:03 +01:00
parent fcf5fe70f3
commit c994506abc

View File

@ -107,47 +107,6 @@ class PreviewView(context: Context, callback: SurfaceHolder.Callback) :
}
}
private fun getSize(contentSize: Size, containerSize: Size, resizeMode: ResizeMode): Size {
var contentSize = contentSize
// Swap dimensions if orientation is landscape
if (orientation.isLandscape()) {
contentSize = Size(contentSize.height, contentSize.width)
}
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
ResizeMode.CONTAIN -> contentAspectRatio < containerAspectRatio
}
return if (widthOverHeight) {
// Scale by width to cover height
val scaledWidth = containerSize.height * contentAspectRatio
Size(scaledWidth.roundToInt(), containerSize.height)
} else {
// Scale by height to cover width
val scaledHeight = containerSize.width / contentAspectRatio
Size(containerSize.width, scaledHeight.roundToInt())
}
}
@SuppressLint("DrawAllocation")
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val measuredViewSize = Size(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec))
val surfaceSize = size.rotatedBy(inputOrientation)
val fittedSize = getSize(surfaceSize, measuredViewSize, resizeMode)
Log.i(TAG, "PreviewView is $measuredViewSize rendering $surfaceSize orientation ($orientation). Resizing to: $fittedSize ($resizeMode)")
setMeasuredDimension(fittedSize.width, fittedSize.height)
}
companion object {
private const val TAG = "PreviewView"
}