可设置宽高比的图片控件:
AspectRatioImageView
class AspectRatioImageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {
var ratio: Float = DEFAULT_RATIO
init {
attrs?.let {
context.obtainStyledAttributes(it, R.styleable.AspectRatioImageView).apply {
ratio = getFloat(R.styleable.AspectRatioImageView_viewAspectRatio, DEFAULT_RATIO)
recycle()
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (ratio > 0) {
var width = measuredWidth
var height = measuredHeight
when {
width > 0 -> height = (width / ratio).toInt()
height > 0 -> width = (height * ratio).toInt()
else -> return
}
setMeasuredDimension(width, height)
}
}
fun setAspectRatio(ratio: Float) {
if (ratio < 0) {
return
}
this.ratio = ratio
requestLayout()
}
companion object {
const val DEFAULT_RATIO = -1F
}
}
attrs.xml
<declare-styleable name="AspectRatioImageView">
<attr format="float" name="viewAspectRatio"/>
</declare-styleable>
引用:
<com.qianfanyun.base.wedgit.AspectRatioImageView
android:id="@+id/img_bg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
app:viewAspectRatio="1" />