为什么当我创建这个新位图时它的背景是深灰色的?如何将其设置为与布局背景颜色相同的颜色?

Why when I create this new Bitmap its background is dark grey? How can I set it to the same color of the layout background?

我是 Android 的新手,遇到以下问题。

我创建了这张图片:

使用此方法:

public static Bitmap createRankingImg(Context context, int difficulty) {

    // Create a Bitmap image starting from the star.png into the "/res/drawable/" directory:
    Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.chef_hat_ok_resize);


    // Create a new image bitmap having width to hold 5 star.png image:
    Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth() * 7, myBitmap.getHeight(), Bitmap.Config.RGB_565);

    Canvas tempCanvas = new Canvas(tempBitmap);

    // Draw the image bitmap into the cavas:
    tempCanvas.drawBitmap(myBitmap, 0, 0, null);        // FROM 0 TO 1
    tempCanvas.drawBitmap(myBitmap, (float) (myBitmap.getWidth() * 1.5), 0, null);       // FROM 1.5 TO 2.5
    tempCanvas.drawBitmap(myBitmap, (float) ( myBitmap.getWidth() * 3), 0, null);        // FROM 3 TO 4
    tempCanvas.drawBitmap(myBitmap, (float) (myBitmap.getWidth() * 4.5), 0, null);       // FROM 4.5 TO 5.5
    tempCanvas.drawBitmap(myBitmap, (float) (myBitmap.getWidth() * 6), 0, null);       // FROM 6 TO 7


    return tempBitmap;

}

它工作得很好,唯一的问题是在 space 之间的一个 chef_hat_ok_resize.png 图像和下一个空 space有灰色暗色。

我希望它具有与布局背景相同的颜色(白色)。

我想也许这取决于这条线:

Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth() * 7, myBitmap.getHeight(), Bitmap.Config.RGB_565);

为什么?我错过了什么?我该如何解决这个问题?

方法一

在您的 drawBitmap 调用之前,插入

tempCanvas.drawColor(Color.WHITE);

您看到的背景颜色只是黑色,这就是这种类型的空新位图将被初始化为的颜色(全为零)。

方法二

使用支持透明度的位图配置:

Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth() * 7, myBitmap.getHeight(), Bitmap.Config.ARGB_8888);

在这种情况下,位图将被初始化为透明黑色(再次全为零),并且在未绘制图标的地方,位图后面的任何内容都将可见。

这两种方法的区别在于透明度需要具有 alpha 通道的位图。首选哪种方法将取决于您应用程序的其他详细信息。

例如,

RGB_565ARGB_8888 更紧凑(但 ARGB_4444 也支持透明度)。

使用透明度也会减慢动画速度,因为部分覆盖的视图需要更频繁地重绘。