[android] Fit Image in ImageButton in Android

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);      
    }

This question is related to android image android-linearlayout scale imagebutton

The answer is


I'm using the following code in xml

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

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

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


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

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


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


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
                }
            });

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to android-linearlayout

Android LinearLayout : Add border with shadow around a LinearLayout How to add a fragment to a programmatically generated layout? How to center the content inside a linear layout? How to add (vertical) divider to a horizontal LinearLayout? Fit Image in ImageButton in Android How can I create a border around an Android LinearLayout? Put buttons at bottom of screen with LinearLayout? How to show shadow around the linearlayout in Android? How to add border around linear layout except at the bottom? How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

Examples related to scale

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis Understanding `scale` in R simple Jquery hover enlarge Adjusting the Xcode iPhone simulator scale and size How to scale Docker containers in production Scale the contents of a div by a percentage? Fit Image in ImageButton in Android Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions? How can I shrink the drawable on a button? Auto Scale TextView Text to Fit within Bounds

Examples related to imagebutton

jQuery UI Dialog - missing close icon Fit Image in ImageButton in Android Android Imagebutton change Image OnClick How to pass multiple values through command argument in Asp.net? How to set transparent background for Image Button in code? How to show the text on a ImageButton? How to add image for button in android? How to have a transparent ImageButton: Android ImageButton in Android Android ImageButton with a selected state?