我有一个imageview。我想让它的宽度为fill_parent。我想让它的高等于宽度。例如:
<ImageView
android:layout_width="fill_parent"
android:layout_height="whatever the width ends up being" />
在布局文件中,不需要创建自己的视图类,这样的事情可能吗?
谢谢
我有一个imageview。我想让它的宽度为fill_parent。我想让它的高等于宽度。例如:
<ImageView
android:layout_width="fill_parent"
android:layout_height="whatever the width ends up being" />
在布局文件中,不需要创建自己的视图类,这样的事情可能吗?
谢谢
当前回答
我不认为有任何方法可以在XML布局文件中这样做,我不认为android:scaleType属性会像你想要的那样工作。 唯一的方法是通过编程来实现。您可以将宽度设置为fill_parent,并且可以将屏幕宽度作为视图的高度,也可以使用View. getwidth()方法。
其他回答
下面是我解决这个问题的方法:
int pHeight = picture.getHeight();
int pWidth = picture.getWidth();
int vWidth = preview.getWidth();
preview.getLayoutParams().height = (int)(vWidth*((double)pHeight/pWidth));
preview - imageView,宽度设置为“match_parent”,scaleType设置为“cropCenter”
在imageView src中设置的位图对象。
这对我来说很有效。
如果你的图像视图在一个约束布局中,你可以使用以下约束来创建一个正方形的图像视图,确保使用1:1来制作正方形
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/ivImageView"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
光靠布局是做不到的,我试过了。我最终写了一个非常简单的类来处理它,你可以在github上查看。它是一个更大项目的一部分,但一点复制和粘贴就能解决问题(在Apache 2.0下授权)
本质上,你只需要设置高度/宽度等于另一个维度(取决于你想缩放它的方式)
注意:您可以使用scaleType属性在不使用自定义类的情况下将其设置为正方形,但视图的边界超出了可见图像,如果将其他视图放置在其附近,则会产生问题。
在Android中26.0.0 PercentRelativeLayout已弃用。
解决这个问题的最好方法是使用这样的ConstraintLayout:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
android:src="@drawable/you_image"
app:layout_constraintDimensionRatio="1:1"/>
</android.support.constraint.ConstraintLayout>
下面是一个关于如何将ConstraintLayout添加到项目中的教程。
也许这能回答你的问题:
<ImageView
android:id="@+id/cover_image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:adjustViewBounds="true" />
对于这种特定的情况,您可以忽略scaleType属性。