我有以下渐变(动态生成):
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。
关于我如何解决这个问题的任何想法?
提前致谢
答案 0 :(得分:4)
我终于从您的回复中找到了解决方案。我粘贴了可能需要它的人的代码:
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;
}
答案 1 :(得分:1)
Bitmap.createBitmap()
Canvas
new Canvas(bitmap)
draw(canvas)
GradientDrawable
答案 2 :(得分:0)
您可以在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;
}