From 9454f3e4d1d222799049b00f3d84b274c3e02ee6 Mon Sep 17 00:00:00 2001 From: Ali Asadi Date: Fri, 10 Dec 2021 11:53:46 +0200 Subject: [PATCH] Add TopCrop option to ScaleType (#372) --- .../io/fotoapparat/parameter/ScaleType.kt | 9 +++++++- .../java/io/fotoapparat/view/CameraView.kt | 23 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/fotoapparat/src/main/java/io/fotoapparat/parameter/ScaleType.kt b/fotoapparat/src/main/java/io/fotoapparat/parameter/ScaleType.kt index 2bef1f56..b871f13c 100644 --- a/fotoapparat/src/main/java/io/fotoapparat/parameter/ScaleType.kt +++ b/fotoapparat/src/main/java/io/fotoapparat/parameter/ScaleType.kt @@ -15,6 +15,13 @@ enum class ScaleType { * The preview will be scaled so as its one dimensions will be equal and the other one equal or * smaller than the corresponding dimension of the view */ - CenterInside + CenterInside, + + + /** + * The preview will be scaled so as its one dimensions will be equal and the other one equal or + * larger than the corresponding dimension of the view with focus on the top part + */ + TopCrop, } \ No newline at end of file diff --git a/fotoapparat/src/main/java/io/fotoapparat/view/CameraView.kt b/fotoapparat/src/main/java/io/fotoapparat/view/CameraView.kt index 5e029f85..ff03e358 100644 --- a/fotoapparat/src/main/java/io/fotoapparat/view/CameraView.kt +++ b/fotoapparat/src/main/java/io/fotoapparat/view/CameraView.kt @@ -82,6 +82,7 @@ private fun ViewGroup.layoutTextureView( ) = when (scaleType) { ScaleType.CenterInside -> previewResolution?.centerInside(this) ScaleType.CenterCrop -> previewResolution?.centerCrop(this) + ScaleType.TopCrop -> previewResolution?.topCrop(this) else -> null } @@ -129,6 +130,28 @@ private fun Resolution.centerCrop(view: ViewGroup) { view.layoutChildrenAt(rect) } +private fun Resolution.topCrop(view: ViewGroup) { + val scale = Math.max( + view.measuredWidth / width.toFloat(), + view.measuredHeight / height.toFloat() + ) + + val width = (width * scale).toInt() + val height = (height * scale).toInt() + + val extraX = Math.max(0, width - view.measuredWidth) + + val rect = Rect( + -extraX / 2, + 0, + width - extraX / 2, + height + ) + + view.layoutChildrenAt(rect) +} + + private fun ViewGroup.layoutChildrenAt(rect: Rect) { (0 until childCount).forEach { getChildAt(it).layout(