Skip to content

Instantly share code, notes, and snippets.

@tprochazka
Created September 6, 2021 01:39
Show Gist options
  • Save tprochazka/f651b1fe12ee9ccbf6d70be611a9333d to your computer and use it in GitHub Desktop.
Save tprochazka/f651b1fe12ee9ccbf6d70be611a9333d to your computer and use it in GitHub Desktop.
Layout manager that will simply render everything inside in requested size and then scale down it to fit the parent size.
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import androidx.core.view.children
import kotlin.math.roundToInt
/**
* Layout manager that will simply render everything inside in requested size
* and then scale down it to fit the parent size.
*
* Current implementation is the simplest possible and evaluate just width
* of all children and scale them down if width is bigger than parent view itself.
*
* If all children fit parent it works as LinerLayout.
*
* Works only with vertical Linear Layout orientation.
*
* @author Tomáš Procházka
*/
class ScaleToFitLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0,
) : LinearLayout(
context,
attrs,
defStyleAttr,
defStyleRes
) {
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
super.onLayout(changed, left, top, right, bottom)
children.forEach { child: View ->
if (child.width > width) {
// Only if child is bigger than parent
val scale = width.toFloat() / (child.width * 1f)
child.scaleX *= scale
child.scaleY *= scale
val nleft = ((width - child.width) / 2f).roundToInt()
// layout is evalueated before scale down, so we need to render more than visible area to be able to scale it down
child.layout(nleft, child.top, child.width + nleft, child.bottom)
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
children.forEach {
// we will ignore parent size and allow to use as much space as possible
it.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment