Android drawBitmap: Canvas Guide

The Canvas class in Android offers a drawBitmap() method for drawing a bitmap onto the canvas. This method has several overloaded versions, with commonly used parameters including:

  1. Bitmap bitmap: The bitmap object to be drawn.
  2. The coordinates of the top left corner of the bitmap on the canvas are specified by float left, float top.
  3. Paintbrush: a tool used when drawing bitmaps.

Here is a simple example code that demonstrates how to use the drawBitmap() method to draw a bitmap on a canvas.

// 创建一个位图对象
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);

// 在onDraw()方法中使用Canvas绘制位图
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    
    // 绘制位图到画布上,左上角坐标为(0, 0)
    canvas.drawBitmap(bitmap, 0, 0, null);
}

In the above code, the first step is to load an image from a resource file as a bitmap object using BitmapFactory.decodeResource() method, and then draw the bitmap onto the canvas in the onDraw() method using the drawBitmap() method of the Canvas.

It is important to note that to prevent memory leaks, it is typically necessary to call the bitmap.recycle() method after using the bitmap to release its memory resources.

bannerAds