android - 将 GradientDrawable 转换为位图

标签 android drawable android-custom-view android-drawable android-bitmap

我有以下渐变(动态生成):

    GradientDrawable dynamicDrawable = new GradientDrawable();
    dynamicDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
    dynamicDrawable.setUseLevel(false);
    int colors[] = new int[3];
    colors[0] = Color.parseColor("#711234");
    colors[1] = Color.parseColor("#269869");
    colors[2] = Color.parseColor("#269869");
    dynamicDrawable.setColors(colors);

我想使用 onDraw 方法在 View 中设置该可绘制对象。

当我想将 Drawable 分配给位图时,我使用转换 (BitmapDrawable),但在这种情况下这是不可能的,因为gradientDrawable 无法转换为 BitmapDrawable。

知道如何解决这个问题吗?

提前致谢

最佳答案

我终于从你的回复中找到了解决方案。我将代码粘贴给可能需要它的人:

private Bitmap createDynamicGradient(String color) {
    int colors[] = new int[3];
    colors[0] = Color.parseColor(color);
    colors[1] = Color.parseColor("#123456");
    colors[2] = Color.parseColor("#123456");

    LinearGradient gradient = new LinearGradient(0, 0, 0, 400, Color.RED, Color.TRANSPARENT, Shader.TileMode.CLAMP);
    Paint p = new Paint();
    p.setDither(true);
    p.setShader(gradient);

    Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    canvas.drawRect(new RectF(0, 0, getWidth(), getHeight()), p);

    return bitmap;
}

关于android - 将 GradientDrawable 转换为位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33181417/

相关文章:

Android Button drawableLeft - 如何对其进行硬编码(无 xml)

android - 拐角半径和可在代码中绘制的项目

android - Facebook 使用什么库通过拖动来关闭图像?

android - Android 设备 sleep 的定义是什么?

android - 如何使用 KSOAP 故障消息

android - 使用最小宽度配置限定符

android - 自定义 ListView 不会替换 View

android - 如何更改起点drawrect customview android

Android更复杂的ListView教程

android - 如何捕捉安卓设备的视频/屏幕截图