Mutates the state of background BitmapDrawables so that TileMode.REPEAT works properly - Android Graphics

Android examples for Graphics:Drawable

Description

Mutates the state of background BitmapDrawables so that TileMode.REPEAT works properly

Demo Code


//package com.java2s;

import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.StateListDrawable;
import android.view.View;

public class Main {
    /** Mutates the state of background BitmapDrawables so that TileMode.REPEAT works properly **/
    public static void fixBackgroundRepeat(View view) {
        Drawable bg = view.getBackground();
        fixDrawableRepeat(bg);//from  w w  w  . j a va  2 s .c om
    }

    /** Dispatches Drawable repeat fixes based on the type of the Drawable **/
    public static void fixDrawableRepeat(Drawable d) {
        if (d != null) {
            if (d instanceof BitmapDrawable)
                fixBitmapRepeat((BitmapDrawable) d);
            else if (d instanceof LayerDrawable)
                fixLayerRepeat((LayerDrawable) d);
            else if (d instanceof StateListDrawable)
                fixStateListRepeat((StateListDrawable) d);
        }
    }

    /** Mutate the bitmap and reset tilemode **/
    public static void fixBitmapRepeat(BitmapDrawable bmp) {
        bmp.mutate(); // make sure that we aren't sharing state anymore
        bmp.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
    }

    /** Go through layers and dispatch them via fixDrawableRepeat **/
    public static void fixLayerRepeat(LayerDrawable lyr) {
        for (int i = 0; i < lyr.getNumberOfLayers(); i++) {
            fixDrawableRepeat(lyr.getDrawable(i));
        }
    }

    /** There's a limitation where we can only get the current Drawable, so that's the only one that can be mutated **/
    private static void fixStateListRepeat(StateListDrawable d) {
        fixDrawableRepeat(d.getCurrent());
    }
}

Related Tutorials