【问题标题】:Why I obtain a black background when I create a new Bitmap in this way? How can I obtain a transparent backround?用这种方式新建Bitmap时为什么会得到黑色背景?如何获得透明背景?
【发布时间】:2016-07-25 15:25:04
【问题描述】:

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

我已经实现了使用 Canvas 绘制 Bitmap 的代码(它绘制了 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

具体是什么意思?

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

【问题讨论】:

  • 将其更改为 Bitmap.config.ARGB_8888。因为透明度是由 Alpha 通道(ARGB 中的“A”)定义的。使用“RGB”没有 Alpha 通道 => 没有透明度
  • 还要确保png 本身具有透明背景...white 不透明
  • RGB_565 表示红色使用 5 位,绿色使用 6 位,蓝色使用 5 位,alpha 使用 0 位。它以字节为单位制作更小的位图,但颜色深度更小且没有透明度。对于透明度,您通常对每种颜色使用 ARGB_8888- 8,对透明度使用 8。

标签: java android android-image android-bitmap createbitmap


【解决方案1】:

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

Android Doc for createBitmap

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

所以,改为使用 Bitmap.Config.ARGB_8888 作为最后一个参数。

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

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2018-04-25
    • 2013-02-09
    • 2011-02-12
    • 1970-01-01
    • 2013-09-18
    相关资源
    最近更新 更多