【问题标题】:Resize the image user inputted into the ImageView调整用户输入到 ImageView 中的图像大小
【发布时间】:2017-02-23 13:07:18
【问题描述】:

所以我有一个 ImageView,它将从数据库中检索图像以在程序中显示它。但是,我希望将检索到的图像调整为特定的高度和宽度(因此它不会填满整个屏幕)

我希望它的宽度是 150dp,而它的高度是 230dp。

但是,数据库中的图片可能是空的,因此我们不能设置ImageView的高度和宽度,否则布局上会出现空白。

那么,如何调整图片大小?

以下是我当前的代码:

<ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dp"
      android:layout_marginBottom="10dp"
      android:layout_gravity="center"
      android:id="@+id/Img" />

【问题讨论】:

    标签: android xml imageview


    【解决方案1】:

    使用刻度类型 fitXY

      <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginTop="10dp"
              android:layout_marginBottom="10dp"
              android:scaleType="fitXY"
              android:layout_gravity="center"
              android:id="@+id/Img" />
    

    【讨论】:

      【解决方案2】:

      如果您愿意使用 Picasso,您可以像这样轻松调整图片大小:

      Picasso  
          .with(context)
          .load(image)
          .resize(150, 230)
          .into(imageView);
      

      还有很多其他的可能,你可以在这里查看: https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit

      【讨论】:

        【解决方案3】:

        首先在您的 dimens.xml 文件中创建值:

        <dimen name="imageview_width">150dp</dimen> 
        <dimen name="imageview_height">230dp</dimen> 
        

        然后,在您处理从数据库接收到的图像的代码中:

        if(image != null){
            imageview.getLayoutParams().height = (int) getResources().getDimension(R.dimen.imageview_height);
            imageview.getLayoutParams().width = (int) getResources().getDimension(R.dimen.imageview_width);
            imageview.setimagedrawable(img); // or any way that suits you.
            }
        

        通过这种方式,您可以将 dp 值转换为像素值,并且可以在图像视图从 xml 膨胀后以编程方式更改它的大小。

        【讨论】:

          【解决方案4】:

          我不确定是否了解您的需求。但是,如果您希望将视图调整为 150x230,则需要使用 rajahsekar 的答案。但是,如果您还希望您的 Imaview 在 DB 中的 Image 为空时不存在,您可以通过编程方式进行设置:

          imageView.setVisibility(View.GONE)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-02-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-02-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多