Search code examples
androidxmlscale

XML Drawable consisting of two images


I am trying to create a XML Drawable which I would use instead of the default marker in OSMDroid.
This is what it should look like in the end:

custom marker

The black part will be loaded while creating the marker, as every marker will have a different image there. (these will be loaded from a Database if that´s important)

I tried to create a XML Drawable, and it kinda works, but the black part seems to be scaled to fit the image, thus making the marker just a big black square. (without the black part it works fine)

My current XML:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:drawable="@drawable/marker"/>         // main

    <item android:drawable="@drawable/markerfill" />    // black part

</layer-list>

I tried using a scale for the second item, but as I looked into scales, it looked like I can´t use scales for this.

What I want:
I load the black box into the "main" part, resize it if necessary (while keeping the proportions) and change it from Java-Code. I will be using this marker for OSMDroid.

What would be the best approach for this?


Solution

  • What I want: I load the black box into the "main" part, resize it if necessary (while keeping the proportions) and change it from Java-Code. I will be using this marker for OSMDroid.

    If the first layer image will not be resized/scaled when used(I don't know how OSMDroid manages that marker) then you could use the current approach of a LayerDrawable and "place" the dynamic image with LayerDrawable.setLayerInset():

    public Drawable makeBasicMarker(Bitmap bitmap) {
            Drawable[] layers = new Drawable[2];
            layers[0] = new BitmapDrawable(getResources(),
                    BitmapFactory.decodeResource(getResources(), R.drawable.marker));
            layers[1] = new BitmapDrawable(getResources(), bitmap);
            LayerDrawable ld = new LayerDrawable(layers);
            ld.setLayerInset(1, xx, xx, xx, xx); // xx would be the values needed so bitmap ends in the upper part of the image
            return ld;
        }
    

    If the image is scaled then you need to make your own Drawable and draw the parts yourself placing them appropriately.