How to combine shape drawable and drawable into single drawable

1.3k Views Asked by At

I am generating shape drawable and drawable runtime in android programmatically. What all I need is to combine two drawable into single drawable. I tried to implement through following methods, but nothing seems to work out.

Sample code to combine two drawables into single using LayerDrawable

public static LayerDrawable drawCircleWithIcon (Context context, int width, int height, int color,Drawable drawable) {

        ShapeDrawable oval = new ShapeDrawable (new OvalShape ());
        oval.setIntrinsicHeight (height);
        oval.setIntrinsicWidth (width);
        oval.getPaint ().setColor (color);

        Drawable[] layers = new Drawable[2];
        layers[0] = drawable;
        layers[1] = oval;

        LayerDrawable composite1 = new LayerDrawable (layers);

        return composite1;
    }

Arguments I am passing:

width - width of the circle  
height - height of the circle  
color - color of the circle
drawable - icon that needs to be fit inside the ShapeDrawable (i.e. Round circle inside placed with icon) 

My requirement:

I need to combine two drawables (one is ShapeDrawable and drawable). The output must be like as following

enter image description here

Kindly please help me with your solutions or alternate methods to merge two drawable into one drawable icon. Thanks in advance.

1

There are 1 best solutions below

3
On

You can try using an imageview an set the properties backgroundDrawable and imageDrawable or imageResource.

yourImageView.setBackgroundDrawable(yourShape);
YourImageView.setImageDrawable(yourImage);

To adjust the drawable and keep aspect ratio try using, his methods.

yourImageView.setAdjustViewBounds(true);
yourImageView.setScaleType(ScaleType.FIT_CENTER);

Due to this answer does't adjust to the question, if what you want is to create a single image combining multiple drawables, you can try something like this:

Resources res = getResources();

// Front image
Bitmap image = BitmapFactory.decodeResource(res, R.drawable.frontImage);

// The rounded background
Bitmap background = BitmapFactory.decodeResource(res, shapeDrawable);
RoundedBitmapDrawable dr = RoundedBitmapDrawableFactory.create(res, background);
dr.setCornerRadius(Math.max(background.getWidth(), background.getHeight()) / 2.0f);

Bitmap combined = Bitmap.createBitmap(dr.getWidth(), dr.getHeight(), Bitmap.Config.ARGB_8888);

// Creates the combined drawable
Canvas canvas = new Canvas(combined);
canvas.drawBitmap(dr,0, 0, null);
canvas.drawBitmap(image, dr.getWidht() / 2.0f, dr.getHeight() / 2.0f, null);

I have not tried the code above, but i'm showing something could help you.