[英]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.