一 示例
二 代码
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.test.ui.video.ui.image.topfit.TopFitImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/purple_200"
android:scaleType="fitXY" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="largeWidthStretch"
android:text="2/1宽高比" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="equalWidthStretch"
android:text="1/1宽高比" />
</LinearLayout>
</FrameLayout>
package com.example.test.ui.video.ui.image.topfit
import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
class TopFitImageView : androidx.appcompat.widget.AppCompatImageView {
constructor(context: Context?) : super(context!!)
constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context!!,
attrs,
defStyleAttr
)
val minWHRatio = 1
val maxWHRatio = 2
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val drawable = drawable
if (drawable != null) {
val whRatio = drawable.intrinsicWidth.toFloat() / drawable.intrinsicHeight.toFloat()
val width = MeasureSpec.getSize(widthMeasureSpec)
var height = (width / whRatio).toInt()
if (whRatio > maxWHRatio) {
height = width / maxWHRatio
} else if (whRatio < minWHRatio) {
height = width
}
setMeasuredDimension(width, height)
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
}
override fun setImageBitmap(bm: Bitmap?) {
if (bm != null && bm.width > 0 && bm.height > 0) {
var height = bm.height
val whRatio = bm.width / bm.height
// if (whRatio > maxWHRatio) {
// height = bm.width / maxWHRatio
// } else
if (whRatio < minWHRatio) {
height = bm.width
}
super.setImageBitmap(Bitmap.createBitmap(bm, 0, 0, bm.width, height))
return
}
super.setImageBitmap(bm)
}
}