【发布时间】: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