动态9patch解决方案

public class NinePatchBitmapFactory {
    private static final int NO_COLOR = 0x00000001;

    private static final int TRANSPARENT_COLOR = 0x00000000;

    public static NinePatchDrawable createNinePatchDrawable(Resources res, Bitmap bitmap) {
        RangeLists rangeLists = checkBitmap(bitmap);
        Bitmap trimedBitmap = trimBitmap(bitmap);
        NinePatchDrawable drawable = createNinePatchWithCapInsets( res , trimedBitmap , rangeLists.rangeListX , rangeLists.rangeListY , null );
        return drawable;
    }


    public static NinePatchDrawable createNinePatchWithCapInsets(Resources res, Bitmap bitmap,
                                                                 List rangeListX, List rangeListY , String srcName) {
        ByteBuffer buffer = getByteBuffer(rangeListX,rangeListY);
        NinePatchDrawable drawable = new NinePatchDrawable(res,bitmap, buffer.array(), new Rect(), srcName);
        return drawable;
    }

    private static ByteBuffer getByteBuffer(List rangeListX, List rangeListY) {
        ByteBuffer buffer = ByteBuffer.allocate(4 + 4*7 + 4*2*rangeListX.size() + 4*2*rangeListY.size() + 4*9).order(ByteOrder.nativeOrder());
        buffer.put((byte)0x01); // was serialised
        buffer.put((byte) (rangeListX.size() * 2) ); // x div
        buffer.put((byte) (rangeListY.size() * 2) ); // y div
        buffer.put((byte)0x09); // color

        // skip
        buffer.putInt(0);
        buffer.putInt(0);

        // padding
        buffer.putInt(0);
        buffer.putInt(0);
        buffer.putInt(0);
        buffer.putInt(0);

        // skip 4 bytes
        buffer.putInt(0);

        for (Range range : rangeListX) {
            buffer.putInt( range.start );
            buffer.putInt( range.end );
        }
        for (Range range : rangeListY) {
            buffer.putInt( range.start);
            buffer.putInt( range.end );
        }
        buffer.putInt(NO_COLOR);
        buffer.putInt(NO_COLOR);
        buffer.putInt(NO_COLOR);
        buffer.putInt(NO_COLOR);
        buffer.putInt(NO_COLOR);
        buffer.putInt(NO_COLOR);
        buffer.putInt(NO_COLOR);
        buffer.putInt(NO_COLOR);
        buffer.putInt(NO_COLOR);

        return buffer;


    }

    public static class RangeLists {
        public List rangeListX;
        public List rangeListY;
    }

    public static class Range {
        public int start;
        public int end;
    }

    public static RangeLists checkBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();


        List rangeListX = new ArrayList();

        int pos = -1;
        for (int i=1;i rangeListY = new ArrayList();

        pos = -1;
        for (int i=1;i

你可能感兴趣的:(动态9patch解决方案)