Android Picasso nine patch image from url

2019-07-27 10:59发布

问题:

I have a problem loading nine patch images from url into a view as the view's background.

I can load nine patch images from resources which works fine.

I set the target for Picasso as follows:

view.setTag(new Target() {

    @Override
    public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
        Log.d("LOG", bitmap.getWidth() + "   " + bitmap.getHeight());

        BitmapDrawable bitmapDrawable = new BitmapDrawable(activity.getResources(), bitmap);

        byte[] ninePatchChunk = bitmap.getNinePatchChunk();
        if (NinePatch.isNinePatchChunk(ninePatchChunk)) {
            view.setBackground(new NinePatchDrawable(activity.getResources(), bitmap, ninePatchChunk, new Rect(), null));
        } else {
            view.setBackground(bitmapDrawable);
        }
    }
}

This function (loading image from assets) works fine:

Picasso.with(activity) 
        .load(R.drawable.nine_patch_button)
        .into(view.getTag()); //view.getTag() is the target

But I need to download the background image from internet.

Picasso.with(activity) 
        .load(uri_to_nine_patch_button)
        .into(view.getTag()); //view.getTag() is the target

In the second case the image is stretched and not displayed as a nine-patch-image. When I load an image from URI, the log output will always be the same (41, 28), but when I load the image from assets, the log output differs from device to device (108, 75 and 38, 27).

In the first case with same output bitmap.getNinePatchChunk() is null, image stretched, nothing works.

Any ideas for solution?

Best regards

回答1:

My solution was using this class: https://gist.github.com/knight9999/86bec38071a9e0a781ee