0

我是 Android 开发的新手,我有以下问题。

我已经实现了使用Canvas绘制位图的代码(它绘制了 5 个并排的图标),所以这是我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Retrieve the ImageView having id="star_container" (where to put the star.png image):
    ImageView myImageView = (ImageView) findViewById(R.id.star_container);

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

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

    /* Attach a brand new canvas to this new Bitmap.
       The Canvas class holds the "draw" calls. To draw something, you need 4 basic components:
       1) a Bitmap to hold the pixels.
       2) a Canvas to host the draw calls (writing into the bitmap).
       3) a drawing primitive (e.g. Rect, Path, text, Bitmap).
       4) a paint (to describe the colors and styles for the drawing).
     */
    Canvas tempCanvas = new Canvas(tempBitmap);

    // Draw the image bitmap into the cavas:
    tempCanvas.drawBitmap(myBitmap, 0, 0, null);
    tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth(), 0, null);
    tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth() * 2, 0, null);
    tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth() * 3, 0, null);
    tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth() * 4, 0, null);

    myImageView.setImageDrawable(new BitmapDrawable(getResources(), tempBitmap));

}

所以它工作正常,图像被正确创建,并且显示了 5 个star.png图像,一个并排显示)。

唯一的问题是新图像的背景(在star.png显示的图像后面)是黑色的。star.png图像具有白色背景。

我认为这取决于这一行:

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

特别是Bitmap.Config.RGB_565

究竟是什么意思?

如何更改此值以获得透明背景?(或至少改变颜色,例如获得白色背景)

4

1 回答 1

2

在 Android 文档中,createBitmap您会发现:

用于 createBitmap 的 Android 文档

(对于最后一个参数)如果配置不支持每像素 alpha(例如 RGB_565),那么 colors[] 中的 alpha 字节将被忽略(假设为 FF)

因此,改为Bitmap.Config.ARGB_8888用作最后一个参数。

在此配置中,每个像素存储在 4 个字节上。

于 2016-07-25T15:35:32.307 回答