Search code examples
javaandroidandroid-image

Display image based on screen size


I have the following image which is 550X257 in drawable folder: enter image description here

It appears differently for different size screen: enter image description here

How do I ensure it fills the parent width no matter what the device is being used. To test it I made the image larger proportionally and put it inside different Density folder but the images comes out even smaller on the bigger screen.

My XML looks something like this:

<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>

Solution

  • You have two options

    first is convert the image for different dpi devices(ldpi,mdpi,hdpi,xdpi) and put the image in folders drawable-ldpi,drawable-mdpi,drawable-hdpi,drawable-xdpi

    above method may not work perfect for you

    second method is you detect the size of the device and set the width and height of image accordingly in pixels

    Detect screensize by this method

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

    now i hope you can determine the width of the image by using either the widthPixels or heightPixels like this: int imgwidth=(int)(widthPixels*0.80);//80 percent of width and calculate the height in same ratio: int imgheight=(imgwidth*originalimageheight)/originalimagewidth;

    after this you can set the width height of image programmatically using LayoutParameters