如何使互联网上的图像在android布局上响应?

问题描述 投票:0回答:1

我在自己的布局上有一个Imageview,直到我填满了从网络上下载的.jpg。事实是,我试图使图像容器响应屏幕尺寸,因为在较大的手机中图像看起来很小。

    public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
    }

    public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String imageUrl="https:url";

        new DownloadImageTask((ImageView) findViewById(R.id.imvAd))
                .execute(imageUrl);
    }
    }

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imvAd"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="10dp"
                tools:ignore="ContentDescription" />

        </LinearLayout>

</LinearLayout>

我不想给出固定值。

关于寻找什么的任何帮助或建议都很好

android imageview responsive-images
1个回答
0
投票

如果您的ImageView是固定的,则可以通过将ScaleType设置为CENTER_CROP或其他相关的缩放比例来缩放图像,以像ImageView那样缩放图像。

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop" />

但是如果您希望ImageView的大小相对于屏幕大小发生变化您可以将Constraintlayout用作父级,并像这样使用layout_constraintDimensionRatio

也不要使用wrap_content,而是可以使用match_parent来适应布局。或使用0dp(在ConstraintLayout中)并在其他两个视图之间限制ImageView。

<androidx.constraintlayout.widget.ConstraintLayout>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1" />
</androidx.constraintlayout.widget.ConstraintLayout>

[另外,我建议使用图像加载器库,例如Glide。它们效率更高,您也可以直接从此处设置比例类型。

© www.soinside.com 2019 - 2024. All rights reserved.