如何自动设置imageview宽度/高度

rqqzpn5f  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(431)

我有一张宽高比为(高)3:(宽)1的图片,我希望这张图片适合屏幕的宽度,并保持宽高比。
例如,如果屏幕宽度为720,则图像宽度为720,图像高度为720 x 3(2160)

shstlldc

shstlldc1#

无约束布局的解决方案。

class AspectRatioImageView @JvmOverloads constructor(
  context: Context,
  attrs: AttributeSet? = null,
  defStyleAttr: Int = 0
): AppCompatImageView(context, attrs, defStyleAttr) {

  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    var height = (measuredWidth * 3 ).toInt()

    setMeasuredDimension(width, height)
  }
}

然后可以使用宽度作为 match_parent 还有什么 height 使用时 AspectRatioImageView 在xml中。

smdncfj3

smdncfj32#

嗨,我设法解决了我的问题这里是解决办法:

<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="@drawable/sign1s"
            app:layout_constraintDimensionRatio="W,230:350"
            tools:ignore="MissingConstraints" />

    </androidx.constraintlayout.widget.ConstraintLayout>

相关问题