Skip to content

Instantly share code, notes, and snippets.

@mrmitew
Created August 2, 2018 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrmitew/1d4a977fea89cdd8b378be127c709086 to your computer and use it in GitHub Desktop.
Save mrmitew/1d4a977fea89cdd8b378be127c709086 to your computer and use it in GitHub Desktop.
/**
* 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