set Compound Drawable Size Base On Width - Android Graphics

Android examples for Graphics:Drawable Size

Description

set Compound Drawable Size Base On Width

Demo Code

/**/* w  w w.j av a2  s.  co  m*/
 * UmbalaApp
 *
 * Created by Hoang Anh on 8/10/15.
 * Copyright (c) 2015 Umbala. All rights reserved.
 */
//package com.java2s;

import android.graphics.drawable.Drawable;

import android.widget.Button;

public class Main {
    /**
     * Base on request new width we compute new height
     */
    public static void setCompoundDrawableSizeBaseOnWidth(Button button,
            int newWidth) {
        Drawable[] drawables = button.getCompoundDrawables();
        for (Drawable drawable : drawables) {
            if (drawable == null)
                continue;
            int curWidth = drawable.getIntrinsicWidth();
            int curHeight = drawable.getIntrinsicHeight();

            float scale = 1f * newWidth / curWidth;
            int newHeight = (int) (scale * curHeight);

            drawable.setBounds(0, 0, newWidth, newHeight);
        }
        button.setCompoundDrawables(drawables[0], drawables[1],
                drawables[2], drawables[3]);
    }
}

Related Tutorials