Mike Herasimov
Mike Herasimov

Reputation: 1359

Android force Drawable to be drawn with same height and width

I use this calendar library and I need to provide custom selector drawable. Unfortunately I should make each date cell to have height smaller than width, that's why I set app:mcv_tileHeight to 40dp in xml.

After I provide my selector drawable it gets stretched all over the bounds of cell. But I want it to scale like square, not like rectangle, that being said if width of view (date in my case) is bigger than height I expect to have empty space on left and right.

Below is actual screenshot of what I currently have and what do I want to achieve.

example of what I currently have and want to achieve

I already tried to force square scale inside xml by setting width and height to same values inside <size> attribute of layer-list but it didn't help me.

Also I tried second answer from this question, but it produces crashes

And I tried to extend Drawable class like this, but I am getting NPE with this approach.

public class SquareDrawable extends Drawable {

private Drawable drawable;

public SquareDrawable(Drawable drawable) {
    this.drawable = drawable;
}

@Override
public void setBounds(int left, int top, int right, int bottom) {
    super.setBounds(left, top, right, bottom);
    calculateBounds(right - left, bottom - top);
}

private void calculateBounds(int width, int height) {
    final int radius = Math.min(height, width);
    final int offset = Math.abs(height - width) / 2;

    if (width >= height) {
        drawable.setBounds(offset, 0, radius + offset, height);
    } else {
        drawable.setBounds(0, offset, width, radius + offset);
    }
}

@Override
public void draw(@NonNull Canvas canvas) {
    drawable.draw(canvas);
}

@Override
public void setAlpha(int alpha) {
    drawable.setAlpha(alpha);
}

@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
    drawable.setColorFilter(colorFilter);
}

@Override
public int getOpacity() {
    return drawable.getOpacity();
}
}

Upvotes: 0

Views: 449

Answers (1)

WesJ
WesJ

Reputation: 121

If the drawable is a BitmapDrawable, you should be able to set its gravity to force the image to be centered.

BitmapDrawable bitmap = (BitmapDrawable) getResources().getDrawable(R.color.chat_cardview_color);
bitmap.setGravity(Gravity.center)

A similar question here.

Upvotes: 1

Related Questions