【问题标题】:How to swap the ImageView height and width in xml如何在xml中交换ImageView的高度和宽度
【发布时间】:2019-05-14 04:28:47
【问题描述】:

我的 xml 中有一个 ImageView,如下所示:

<ImageView
    android:id="@+id/ivMessage"
    android:layout_width="@dimen/two_hundred_dp"
    android:layout_height="@dimen/one_sixty_dp"
    android:layout_alignParentRight="true"
    android:layout_margin="@dimen/ten_dp"
    android:background="@drawable/rounded_rectangle_white"
    android:scaleType="fitXY"
    android:padding="@dimen/ten_dp"
    tools:src="@drawable/logo" />

但是我从服务器获取的照片可以是纵向和横向模式,我只想在发生这种情况时交换这个高度和宽度。我试图以编程方式转换那些 dp 但这不起作用并且 dp 已更改。我有什么简单的方法吗?

【问题讨论】:

  • 每张图片的尺寸都必须是 200,160 吗?
  • 是的,但是对于不同的屏幕尺寸,这些值是不同的,例如 200,sw600 是 300,sw720 是 400
  • 你试过wrap_content吗?使用有什么问题?

标签: android android-imageview android-xml android-bitmap


【解决方案1】:

由于您说来自服务器的图像可以是纵向或横向的,因此您可以通过以下方式以编程方式滑动尺寸。

第 1 步。确定图片是横向还是纵向

boolean landscape = false;

if(image.getHeight()>image.getWidth()){
//image is in portrait
landscape = false;
}else{
//image is in landscape
landscape = true;
}

第 2 步。相应地更改高度和宽度

if(landscape){
imageView.setWidth(200);
imageView.setHeight(160);
}
else{
imageView.setWidth(160);
imageView.setHeight(200);
}

【讨论】:

  • 在看到你的回答之前我也是这么做的,非常感谢:)
【解决方案2】:

像这样使用 android:adjustViewBounds 和 maxHeight 或 minHeight 属性:

<ImageView
                android:id="@+id/ivMessage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:maxWidth="@dimen/two_hundred_dp"
                android:maxHeight="@dimen/one_sixty_dp"
                android:adjustViewBounds="true"
                android:layout_margin="@dimen/ten_dp"
                android:background="@drawable/rounded_rectangle_white"
                android:scaleType="fitXY"
                android:padding="@dimen/ten_dp"
                tools:src="@drawable/logo" />

【讨论】:

    猜你喜欢
    • 2014-05-01
    • 2012-02-11
    • 2023-03-18
    • 2017-05-23
    • 1970-01-01
    • 2011-05-15
    • 2020-11-13
    • 2013-02-06
    • 2023-03-23
    相关资源
    最近更新 更多