java - 根据屏幕尺寸显示图像

标签 java android android-image

我在 drawable 文件夹中有以下 550X257 图像: enter image description here

不同尺寸的屏幕显示有所不同: enter image description here

无论使用什么设备,如何确保它填充父宽度。为了测试它,我按比例放大图像并将其放入不同的密度文件夹中,但图像在更大的屏幕上显示得更小。

我的 XML 看起来像这样:

<RelativeLayout 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"
    android:paddingBottom="0dp"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="@drawable/bd" >

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_marginLeft="64dp"
        android:layout_toRightOf="@+id/button1"
        android:text="Button" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="46dp"
        android:layout_marginTop="192dp"
        android:text="Button" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_margin="0dp"
        android:padding="0dp"
        android:src="@drawable/test" />

</RelativeLayout>

最佳答案

你有两个选择

首先是针对不同 dpi 设备(ldpi、mdpi、hdpi、xdpi)转换图像并将图像放入文件夹drawable-ldpi、drawable-mdpi、drawable-hdpi、drawable-xdpi

上述方法可能不太适合您

第二种方法是检测设备的尺寸并相应地设置图像的宽度和高度(以像素为单位)

通过该方法检测屏幕尺寸

    Display display = activity.getWindowManager().getDefaultDisplay();
    DisplayMetrics dm= new DisplayMetrics();
    display.getMetrics(dm);
    Log.i("widthxheight",dm.widthPixels+"x"+dm.heightPixels;

现在我希望您可以使用 widthPixels 或 heightPixels 来确定图像的宽度,如下所示: int imgwidth=(int)(widthPixels*0.80);//宽度的 80% 并按相同比例计算高度:int imgheight=(imgwidth*originalimageheight)/originalimagewidth;

此后,您可以使用 LayoutParameters 以编程方式设置图像的宽度高度

关于java - 根据屏幕尺寸显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18298987/

相关文章:

android - 为什么我的编辑联系人不起作用?

安卓圆形画廊?

android - 在 android 中滚动 listView 时重新加载图像

java - 线程不可理解的行为

java - 在模糊的位置绘制形状

android - 共享库依赖是如何解决的?

android - 如果我选择大图像,OnActivityResult 会崩溃

java - 检查一个字符在字符串中连续出现了多少次

java - 最新版本的 spring boot 问题

javascript - 如何修复 null 不是对象 React Native Splash Screen