Android: compiling 9-patch files to be used outside of the drawable folder?

前端 未结 2 1979
野趣味
野趣味 2021-01-05 20:18

I have a need to load 9-patch files from outside of the drawable folder. This is so that my application can download new skins from a server, for example. I have discovered

2条回答
  •  情书的邮戳
    2021-01-05 21:16

    Here is a workaround which works in my case.

    I have default 9-patch images in my app which I use as message bubbles. I wanted to create downloadable themes which changes the bubbles and other stuff like font colors, etc.

    The *.9.png images included in the drawable folders are the default, they include the black pixels around the image:

    default_outgoing.9.png

    The "custom"/themed bubbles have exactly the same dimensions, placement with minor changes which still uses the same "chunk" area as the default, but these don't include the black pixels or the .9 in the file name:

    pink_round_outgoing.png

    So how does the custom one work and still look fine? Here is a bit of code that fetches the custom image, gets some values from the default 9-patch image and applies them to the custom bitmap:

    //Get the custom replacement image
    Bitmap bitmap = BitmapFactory.decodeFile(folderpath + File.separator + "pink_round_outgoing.png");
    
    //Get padding from the default 9-patch drawable
    Drawable existingDrawable = ContextCompat.getDrawable(this, R.drawable.default_outgoing);
    Rect padding = new Rect();
    if (existingDrawable != null) {
        existingDrawable.getPadding(padding);
    }
    
    //Get 9-patch chunk from the default 9-patch drawable
    Bitmap existingBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.default_outgoing);
    byte[] chunk = existingBitmap.getNinePatchChunk();
    
    //Finally create your custom 9-Patch drawable and set it to background
    NinePatchDrawable d = new NinePatchDrawable(getResources(), bitmap, chunk, padding, null);
    view.setBackground(d);
    

提交回复
热议问题