简体   繁体   English

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

[英]how to set ImageView width/height automatically

I have an Image with aspect ratio of (height)3:(width)1 I want this image to fit the width of the screen and keep the aspect ratio.我有一个纵横比为 (height)3:(width)1 的图像我希望这个图像适合屏幕的宽度并保持纵横比。

for example if the screen width is 720 them the width of the image will be 720 and the height of the image will be 720 x 3 (2160)例如,如果屏幕宽度为 720,则图像的宽度将为 720,图像的高度为 720 x 3 (2160)

Solution without ConstraintLayout.没有 ConstraintLayout 的解决方案。

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)
  }
}

You can then use width as match_parent and any height while using AspectRatioImageView in XML.然后,您可以在 XML 中使用AspectRatioImageView时将宽度用作match_parent和任何height

Hi I managed to solve my problem here is the solution:嗨,我设法解决了我的问题,这是解决方案:

 <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 以编程方式设置 ImageView 的宽度和高度? - Set ImageView width and height programmatically? 以编程方式设置GridView和ImageView的宽度和高度 - Programmatically set the width and height of GridView And ImageView 将 ImageView 高度设置为宽度的 50% - Set ImageView Height 50% Of That's Width 将位图或ImageView的宽度和高度设置为CustomView - Set Width and Height from Bitmap or ImageView to CustomView 如何以编程方式设置imageView的高度? - How to set height of the imageView programatically? 如何为所有屏幕的图像视图定义宽度和高度? - How to define width and height for an imageview for all screens? 如何在不更改ImageView宽度的情况下设置图像的宽度(在ImageView中)? - How to set Width of the image (in ImageView) without changing the width of the ImageView? ImageView宽度和高度以编程方式在TableLayout中 - ImageView Width And Height Programmatically In TableLayout scaleType 和 wrap_content 如何确定 ImageView 的宽度和高度? - How does scaleType and wrap_content determine ImageView width and height? 如何使用Android应用程序中的按钮增加/减少imageView的宽度和高度? - how to increase/decrease imageView width and height with buttons in android app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM