Search code examples
androidxmlbitmap

Android bitmap image size in XML


In my XML file, I'm using bitmap as the following

<bitmap
    android:src="@drawable/Icon"
    android:gravity="center"/>

Here the image width of the icon exceeds the screen.

I tried android:width="100dp" and all. But it isn't working.

Complete XML file:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
      <shape android:shape="rectangle">
            <stroke android:width="3dp" android:color="@color/black" />
            <solid android:color="@color/bg_green" />
        </shape>
   </item>
   <item>
    <bitmap
        android:src="@drawable/Icon"
        android:gravity="center"/>
    </item>
</layer-list>

How can I reduce the width and height of the above bitmap?


Solution

  • From Android Developers I saw that there is no tag for Bitmap XML that allow you to change it size. You need to do this via some Graphic Applications like GIMP. As @Kevin Cooper told already, ideally you need to create different sets of resources (with different sizes) for different screen types.

    But still you can resize it using width and height attributes in ImageView, instead of creating bitmap with different size:

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:scaleType="center"
        android:src="@drawable/Icon" />
    

    If you want to reuse this image in other places, you can create separate style and reuse it:

    // in styles.xml
    <style name="Icon24x24">
        <item name="android:src">@drawable/Icon</item>
        <item name="android:gravity">center</item>
        <item name="android:layout_width">24dp</item>
        <item name="android:layout_height">24dp</item>
    </style>
    
    // in layout.xml
    <ImageView style="@style/Icon24x24"/>
    

    Another way of reusing, may be creating of separate layout file for one ImageView and then including in to other layouts.

    If you want to use this bitmap inside of layer list, please see @Kevin Cooper answer, as he suggested it is possible to add paddings to layer list item:

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:left="20dp"
            android:right="20dp">
            <bitmap
                android:src="@drawable/Icon"
                android:gravity="center" />
        </item>
    </layer-list>
    

    And as @Nicolo also pointed, form API 23, it is possible to set android:width and android:height" to item.