主页 > 开源代码  > 

Android顶部对齐宽度撑满高度等比例缩放及限制最大最小高度

Android顶部对齐宽度撑满高度等比例缩放及限制最大最小高度

一 示例

二 代码

<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android /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) } }
标签:

Android顶部对齐宽度撑满高度等比例缩放及限制最大最小高度由讯客互联开源代码栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Android顶部对齐宽度撑满高度等比例缩放及限制最大最小高度