Created
August 2, 2018 12:05
-
-
Save mrmitew/1d4a977fea89cdd8b378be127c709086 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Makes the height match the width, using the set ratio | |
*/ | |
class RatioImageView : ImageView { | |
private var ratio = 1f | |
constructor(context: Context) : this(context, null, 0) | |
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) | |
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) | |
/** | |
* w:h | |
*/ | |
fun setRatio(r: Float) { | |
ratio = r | |
requestLayout() | |
} | |
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { | |
// Return height as width to force square | |
val width = MeasureSpec.getSize(widthMeasureSpec) | |
val height = (width.toFloat() / ratio).toInt() | |
val wSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY) | |
val hSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) | |
super.onMeasure(wSpec, hSpec) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment