简体   繁体   中英

Converting GradientDrawable to Bitmap

Sorry if I sound too noob. Is there any way to convert a GradientDrawable like

GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation orientation, int[] colors);
into a Bitmap format. I am trying to set the GradientDrawable as the device wallpaper.

Thank you soo much. :)

Try this:

It's not a perfect solution as i've had to hard code the width/height for the GradientDrawable but it seems to work ok regardless.

public static Bitmap drawableToBitmap(Context mContext, int drawableInt) {
    Bitmap bitmap;

    Drawable drawable = getDrawable(mContext, drawableInt);

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if(bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }else if(drawable instanceof GradientDrawable){
        GradientDrawable gradientDrawable = (GradientDrawable) drawable;

        bitmap = Bitmap.createBitmap(140, 140, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        gradientDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        gradientDrawable.draw(canvas);
        return bitmap;
    }

    if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
    } else {
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM