如何将颜色转换为位图?

10

我有一个以整数形式表示的颜色,我想将其转换成位图形式。
有没有什么方法可以这样做?

我尝试过

Drawable d = new ColorDrawable(Color.parseColor("#ffffff"));
Bitmap b = ((BitmapDrawable)d).getbitmap();

但是上述代码会出现错误:“无法将ColorDrawable转换为BitmapDrawable”

是否有其他方法?

实际代码如下:

Palette.generateAsync(BitmapFactory.decodeFile(songArt),
            new Palette.PaletteAsyncListener() {
                @Override
                public void onGenerated(final Palette palette) {
                    if (Build.VERSION.SDK_INT >= 16) {
                        Drawable colorDrawable = new ColorDrawable(palette.getDarkVibrantColor(
                                getResources().getColor(R.color.noti_background)));
                        notificationCompat.bigContentView.setImageViewResource(R.id.noti_color_bg,
                                ((BitmapDrawable) colorDrawable).getBitmap());
                        notificationManager.notify(NOTIFICATION_ID, notificationCompat);
                    }
                }
            }
    );
1个回答

25

有的。你可以这样做:

Bitmap bmp = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
canvas.drawColor(colorInt)

drawColor()中,您还可以使用Color类的方法设置颜色,例如Color.argb(...)Color.rgb(...)

这样,您将获得一个具有指定颜色和尺寸为width/height的位图。

进一步解释:您创建一个具有指定尺寸的Bitmap对象。然后,您创建一个Canvas对象并将Bitmap对象附加到它上面。这样,使用Canvas对象方法绘制的所有内容都会绘制在Bitmap对象上。

最终,您将获得一个包含您所绘制内容的Bitmap对象。


你只应该在 draw(color) 命令中设置一种颜色... 你回答得非常误导人。 - IAmGroot
编辑只是想指出设置颜色的各种方式,因为他正在解析颜色,并且这对我来说是一种奇怪的方式。 - Ilja KO
他说他已经有颜色整数了,为什么还要从字符串解析? - Ilja KO
你已经有现成的位图了吗?那就直接使用它,而不是创建一个新的。否则,你可以自己决定位图的大小...Bitmap类还有像getWidth()或getHeight()这样的方法...顺便说一句,当它起作用时,你可以将我的答案标记为正确的;) - Ilja KO
http://developer.android.com/reference/android/graphics/Bitmap.html http://developer.android.com/reference/android/graphics/Canvas.html - Ilja KO
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接