Fit Image in ImageButton in Android

AndroidImageAndroid LinearlayoutScaleImagebutton

Android Problem Overview


I have 6 ImageButton in my activity, I set images through my code in them ( not using xml).

I want them to cover 75% of the button area. But where as some images cover less area, some are too big to fit into the imageButton. How to programatically resize and show them? Below is the screen shot

enter image description here below is the xml-file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
	android:layout_marginBottom="5sp"
        android:layout_marginLeft="2sp"
        android:layout_marginRight="5sp"
        android:layout_marginTop="0sp"     >
   <LinearLayout
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal">
        <ImageButton          
            
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/button_topleft"
		android:layout_marginBottom="5sp"
        android:layout_marginLeft="2sp"
        android:layout_marginRight="5sp"
        android:layout_marginTop="0sp"
            />
        <ImageButton
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/button_topright"
	android:layout_marginBottom="5sp"
        android:layout_marginLeft="2sp"
        android:layout_marginRight="5sp"
        android:layout_marginTop="0sp"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal">

        <ImageButton
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/button_repeat"
	android:layout_marginBottom="5sp"
        android:layout_marginLeft="2sp"
        android:layout_marginRight="5sp"
        android:layout_marginTop="0sp"     
             />
 
              <ImageButton
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/button_next"
	android:layout_marginBottom="5sp"
        android:layout_marginLeft="2sp"
        android:layout_marginRight="5sp"
        android:layout_marginTop="0sp"     
             />

    </LinearLayout>    
   <LinearLayout
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal">

        <ImageButton
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/button_bottomleft"
	android:layout_marginBottom="5sp"
        android:layout_marginLeft="2sp"
        android:layout_marginRight="5sp"
        android:layout_marginTop="0sp"                                 
             />
        <ImageButton
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/button_bottomright"
 	android:layout_marginBottom="5sp"
        android:layout_marginLeft="2sp"
        android:layout_marginRight="5sp"
        android:layout_marginTop="0sp"                  
            />        
    </LinearLayout>        

</LinearLayout>

and a snippet of myClass.java:

public void addImageButtons()
    {
    	iB_topleft = (ImageButton) findViewById(R.id.button_topleft);
		iB_topright = (ImageButton) findViewById(R.id.button_topright);
		iB_bottomleft = (ImageButton) findViewById(R.id.button_bottomleft);
		iB_bottomright = (ImageButton) findViewById(R.id.button_bottomright);
		iB_next = (ImageButton) findViewById(R.id.button_next);
		iB_repeat = (ImageButton) findViewById(R.id.button_repeat);
    }
    
    public void setImageNextAndRepeat()
    {

 	iB_topleft .setImageResource(R.drawable.aa);
    	iB_topright.setImageResource(R.drawable.bb);   

 	iB_bottomleft.setImageResource(R.drawable.cc);
    	iB_bottomright.setImageResource(R.drawable.dd);   

    	iB_next.setImageResource(R.drawable.next);
    	iB_repeat.setImageResource(R.drawable.repeat);    	
    }

Android Solutions


Solution 1 - Android

>I want them to cover 75% of the button area.

Use android:padding="20dp" (adjust the padding as needed) to control how much the image takes up on the button.

>but where as some images cover less area, some are too big to fit into the imageButton. How to programatically resize and show them?

Use a android:scaleType="fitCenter" to have Android scale the images, and android:adjustViewBounds="true" to have them adjust their bounds due to scaling.

All of these attributes can be set in code on each ImageButton at runtime. However, it is much easier to set and preview in xml in my opinion.

Also, do not use sp for anything other than text size, it is scaled depending on the text size preference the user sets, so your sp dimensions will be larger than your intended if the user has a "large" text setting. Use dp instead, as it is not scaled by the user's text size preference.

Here's a snippet of what each button should look like:

    <ImageButton
        android:id="@+id/button_topleft"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="0dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:padding="20dp"
        android:scaleType="fitCenter" />

Sample Button

Solution 2 - Android

I'm using the following code in xml

android:adjustViewBounds="true"
android:scaleType="centerInside"

Solution 3 - Android

Try to use android:scaleType="fitXY" in i-Imagebutton xml

Solution 4 - Android

I'm using android:scaleType="fitCenter" with satisfaction.

Solution 5 - Android

Refer below link and try to find what you really want:

> ImageView.ScaleType CENTER Center the image in the view, but perform > no scaling. > > ImageView.ScaleType CENTER_CROP Scale the image uniformly (maintain > the image's aspect ratio) so that both dimensions (width and height) > of the image will be equal to or larger than the corresponding > dimension of the view (minus padding). > > ImageView.ScaleType CENTER_INSIDE Scale the image uniformly (maintain > the image's aspect ratio) so that both dimensions (width and height) > of the image will be equal to or less than the corresponding dimension > of the view (minus padding). > > ImageView.ScaleType FIT_CENTER Scale the image using CENTER. > > ImageView.ScaleType FIT_END Scale the image using END. > > ImageView.ScaleType FIT_START Scale the image using START. > > ImageView.ScaleType FIT_XY Scale the image using FILL. > > ImageView.ScaleType MATRIX Scale using the image matrix when drawing.

https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

Solution 6 - Android

I recently found out by accident that since you have more control on a ImageView that you can set an onclicklistener for an image here is a sample of a dynamically created image button

private int id;
private bitmap bmp;
    LinearLayout.LayoutParams familyimagelayout = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT );

    final ImageView familyimage = new ImageView(this);
            familyimage.setBackground(null);
            familyimage.setImageBitmap(bmp);
            familyimage.setScaleType(ImageView.ScaleType.FIT_START);
            familyimage.setAdjustViewBounds(true);
            familyimage.setId(id);
            familyimage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //what you want to do put here
                }
            });

Solution 7 - Android

You can make your ImageButton widget as I did. In my case, I needed a widget with a fixed icon size. Let's start from custom attributes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ImageButtonFixedIconSize">
        <attr name="imageButton_icon" format="reference" />
        <attr name="imageButton_iconWidth" format="dimension" />
        <attr name="imageButton_iconHeight" format="dimension" />
    </declare-styleable>
</resources>

Widget class is quite simple (the key point is padding calculations in onLayout method):

class ImageButtonFixedIconSize
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = android.R.attr.imageButtonStyle
) : ImageButton(context, attrs, defStyleAttr) {

    private lateinit var icon: Drawable

    @Px
    private var iconWidth: Int = 0
    @Px
    private var iconHeight: Int = 0

    init {
        scaleType = ScaleType.FIT_XY
        attrs?.let { retrieveAttributes(it) }
    }

    /**
     *
     */
    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        val width = right - left
        val height = bottom - top

        val horizontalPadding = if(width > iconWidth) (width - iconWidth) / 2 else 0
        val verticalPadding = if(height > iconHeight) (height - iconHeight) / 2 else 0

        setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)

        setImageDrawable(icon)

        super.onLayout(changed, left, top, right, bottom)
    }

    /**
     *
     */
    private fun retrieveAttributes(attrs: AttributeSet) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageButtonFixedIconSize)

        icon = typedArray.getDrawable(R.styleable.ImageButtonFixedIconSize_imageButton_icon)!!

        iconWidth = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconWidth, 0f).toInt()
        iconHeight = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconHeight, 0f).toInt()

        typedArray.recycle()
    }
}

And at last you should use your widget like this:

<com.syleiman.gingermoney.ui.common.controls.ImageButtonFixedIconSize
    android:layout_width="90dp"
    android:layout_height="63dp"

    app:imageButton_icon="@drawable/ic_backspace"
    app:imageButton_iconWidth="20dp"
    app:imageButton_iconHeight="15dp"

    android:id="@+id/backspaceButton"
    tools:ignore="ContentDescription"
    />

Solution 8 - Android

It worked well in my case. First, you download an image and rename it as iconimage, locates it in the drawable folder. You can change the size by setting android:layout_width or android:layout_height. Finally, we have

 <ImageButton
        android:id="@+id/answercall"
        android:layout_width="120dp"
        android:layout_height="80dp"
        android:src="@drawable/iconimage"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:scaleType="fitCenter" />

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRohitView Question on Stackoverflow
Solution 1 - AndroidSteven ByleView Answer on Stackoverflow
Solution 2 - AndroidPratibha SarodeView Answer on Stackoverflow
Solution 3 - AndroidSwap-IOS-AndroidView Answer on Stackoverflow
Solution 4 - AndroidSeraphim'sView Answer on Stackoverflow
Solution 5 - AndroidNhat DinhView Answer on Stackoverflow
Solution 6 - AndroidDavidView Answer on Stackoverflow
Solution 7 - AndroidAlex ShevelevView Answer on Stackoverflow
Solution 8 - AndroidJameView Answer on Stackoverflow