将GradientDrawable转换为位图

时间:2019-01-09 11:21:06

标签: android-studio gradientdrawable

对不起,如果我听起来太傻了。有没有办法像

那样转换GradientDrawable
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation orientation, int[] colors);
转换为位图格式。我正在尝试将GradientDrawable设置为设备墙纸。

非常感谢。 :)

1 个答案:

答案 0 :(得分:0)

尝试一下:

这不是一个完美的解决方案,因为我不得不对GradientDrawable的宽度/高度进行硬编码,但是无论如何似乎都可以。

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;
}