我有以下渐变(动态生成):
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方法在视图中设置drawable。
当我想将Drawable分配给位图时,我使用了转换(BitmapDrawable),但是在这种情况下是不可能的,因为gradientDrawable不能转换为BitmapDrawable。
我对如何解决这个问题有任何想法?
提前致谢
Bitmap.createBitmap()
创建一个可变位图Canvas
创建基于位图的new Canvas(bitmap)
draw(canvas)
上打电话给GradientDrawable
我终于从你的回复中找到了解决方案。我为某人可能需要它粘贴代码:
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: Convert Drawable to Bitmap
public Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
Bitmap mutableBitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mutableBitmap);
drawable.setBounds(0, 0, widthPixels, heightPixels);
drawable.draw(canvas);
return mutableBitmap;
}