【问题标题】:How do you create transparent bitmap with a specific color (not black)?如何创建具有特定颜色(不是黑色)的透明位图?
【发布时间】:2015-08-05 02:35:17
【问题描述】:

透明像素由零的 alpha 值和红色、绿色和蓝色的任意值组成。所以即使一个像素是透明的,它仍然有颜色。

我现在想创建一个完全透明但具有特定颜色(例如白色)的位图。但是通过我尝试的每一种方法,我都会得到一个黑色的透明位图(就像在 png 文件中一样)。

这对我来说非常重要,因为我通过画布在位图上渲染抗锯齿文本。在角落,半透明像素变得更暗。我想要做的是预先用与文本相同的颜色填充位图或画布,但透明。

我的代码

Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
//bitmap manipultion here
Canvas canvas = new Canvas(bitmap);
//canvas manipulation here
canvas.drawText(gText, 0, bounds.height(), paint);

到目前为止我尝试过的(redgreenblue 非零):

画布操作:

这与PorterDuff.Mode.SRC_OVER 的作用相同。我以为SRC 会用源 alpha 和源颜色覆盖目标,还是我错了?

canvas.drawColor(Color.argb(0, red, green, blue), PorterDuff.Mode.SRC);

我也试过这个,但它会生成一个透明的黑色位图。

paint.setColor(Color.argb(0, red, green, blue));
canvas.drawRect(0, 0, w, h, paint);

位图操作:

这不会改变透明(黑色)位图上的任何内容

bitmap.eraseColor(Color.argb(0, red, green, blue));

我尝试了这个,希望第一行用我的颜色覆盖所有内容,然后第二行使其透明。但它给出了一个透明的黑色位图。

bitmap.eraseColor(Color.argb(255, red, green, blue));
bitmap.eraseColor(Color.argb(0, red, green, blue));

这个也生成一个透明的黑色位图

for(int x = 0; x<bitmap.getWidth(); x++){
    for(int y = 0; y<bitmap.getHeight(); y++){
        bitmap.setPixel(x, y, Color.argb(0, red, green, blue));
    }
}

如何生成非黑色透明位图?或者甚至有可能(因为自动压缩)?

【问题讨论】:

  • 你已经有一段时间没有问这个问题了,你还记得你最后做了什么吗?

标签: java android colors android-bitmap porter-duff


【解决方案1】:

尝试在最后一次尝试中将红色绿色和蓝色全部替换为 255,这应该加起来为白色(红色 + 绿色 + 蓝色 == 白色,255 是最大值。

for(int x = 0; x<bitmap.getWidth(); x++){
    for(int y = 0; y<bitmap.getHeight(); y++){
        bitmap.setPixel(x, y, Color.argb(0, 255, 255, 255));
    }
}

【讨论】:

  • 这是我实际尝试过的。我仍然得到一个透明但黑色的位图。 “白”只是一个例子。我写了红色、绿色和蓝色是为了强调我希望它适用于所有颜色。
【解决方案2】:

尝试在 Manifest attr 中添加您的活动:

android:hardwareAccelerated="false"

如果硬件加速删除透明位图,至少你会得到一些答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    相关资源
    最近更新 更多