本文主要是介绍Android 顶部对齐宽度撑满高度等比例缩放及限制最大最小高度,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一 示例
二 代码
<?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.TopFitImageViewandroid:id="@+id/imageView"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@color/purple_200"android:scaleType="fitXY" /><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="largeWidthStretch"android:text="2/1宽高比" /><Buttonandroid: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.topfitimport android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSetclass 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 = 1val maxWHRatio = 2override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {val drawable = drawableif (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.heightval whRatio = bm.width / bm.height
// if (whRatio > maxWHRatio) {
// height = bm.width / maxWHRatio
// } elseif (whRatio < minWHRatio) {height = bm.width}super.setImageBitmap(Bitmap.createBitmap(bm, 0, 0, bm.width, height))return}super.setImageBitmap(bm)}}
这篇关于Android 顶部对齐宽度撑满高度等比例缩放及限制最大最小高度的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!