问题
My problem is this:
I need to create a re-scaled bitmap created using a NinePatch.
My current system creates a Bitmap from a NinePatch file. This then gets fed into a NinePatch (or NinePatchDrawable). I then need to resize it and output to another Bitmap.
I have reviewed this and it helped quite a bit.
Here is my current code:
try {
Bitmap bitmap1 = BitmapFactory.decodeStream(getAssets().open("gfx/head.9.png"));
// Using NinePatch?
NinePatch patch = new NinePatch(bitmap1, bitmap1.getNinePatchChunk(), null);
// Or NinePatchDrawable?
NinePatchDrawable patch = new NinePatchDrawable(bitmap1, bitmap1.getNinePatchChunk(), new Rect(), null);
// Set dimensions from NinePatch and create new bitmap
// Bitmap bitmap2 = ?
}
catch (IOException e) {
e.printStackTrace();
}
回答1:
public static Bitmap get_ninepatch(int id,int x, int y, Context context){
// id is a resource id for a valid ninepatch
Bitmap bitmap = BitmapFactory.decodeResource(
context.getResources(), id);
byte[] chunk = bitmap.getNinePatchChunk();
NinePatchDrawable np_drawable = new NinePatchDrawable(bitmap,
chunk, new Rect(), null);
np_drawable.setBounds(0, 0,x, y);
Bitmap output_bitmap = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output_bitmap);
np_drawable.draw(canvas);
return output_bitmap;
}
X and Y are how big you want the ninepatch to be, context is your application context so you can get your ninepatch resource located at id
Please Note if you intend to use this bitmap in OpenGL X and Y must be powers of 2
回答2:
Are you asking how to draw the NinePatchDrawable? If so, create a Canvas pointing to the Bitmap you want to draw in to, and render the NinePatchDrawable into the Canvas with Drawable.draw(). Be sure to use Drawable.setBounds to set the size you want.
回答3:
Tasomaniac - To get my x and y for that method I am using the window or size of layout or what ever is needed for the nine-patch. If your window or layout is re-sizable just plug in x and y with the width and height maybe with: (eg popwindow)object.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()... and then every time something changes with that particular object or layout, just get the x and y into integers.
来源:https://stackoverflow.com/questions/6802249/bitmap-to-ninepatch-to-new-scaled-bitmap