2013年11月4日 星期一

drawable To Bitmap


2 
Hi Praveen. The drawable I want to set as the wallpaper is not in R.drawable. It is a drawable I downloaded from the web and keep it in an arrayList of type Drawable along with other drawables. –  Rob Jun 14 '10 at 8:37 
1 
i think you have the url values. then my edited answer should help. –  Praveen Jun 14 '10 at 8:49
 
where does str_url come from? I couldn't find any Drawable function related to strings... thanks for your help.–  Rob Jun 14 '10 at 9:08
4 
I think I found something: if "draw" is the drawable I want to convert to a bitmap then: Bitmap bitmap = ((BitmapDrawable)draw).getBitmap(); does the trick! –  Rob Jun 14 '10 at 9:29 
1 
@Rob : if your Drawable is a BitmapDrawable only. (which means that your Drawable is but a wrapper around a Bitmap, actually) –  njzk2 May 28 at 11:47
show 1 more comments

public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}
share|improve this answer
8 
This looks like the only answer that would work for any kind of drawable and also has a quick solution for a drawable that is already a BitmapDrawable. +1 –  Matt Wolfe Jun 6 '12 at 22:37
 
Add @Mauro's solution to this after the check for BitmapDrawable and you've got a very ideal solution with any/ all quicker solutions Incorporated. –  Tom Jul 4 '12 at 23:45
 
This solution works even if the drawable is a 9 patch image. –  Prakash Nadar Aug 15 '12 at 18:47
 
just one amendment: docs says about BitmapDrawable.getBitmap() that it may come back null. I say it may also come back already recycled. –  kellogs Sep 1 '12 at 21:20
7 
Watch out: getIntrinsicWidth() and getIntrinsicHieght() will return -1 if drawable is a solid color.–  S.D. Oct 12 '12 at 13:51

沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...