Save on memory when creating custom bitmap images for a TileProvider

45 views Asked by At

Using a custom TileProvider:

class ObjectTileProvider @Inject constructor(
   val application: Application,
   val repository: ObjectRepository
) : TileProvider {
   override fun getTile(x: Int, y: Int, z: Int): Tile {
      val objects = repository.getObjectsInTile(x, y, z)
      val bitmap = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888)
      val canvas = Canvas(bitmap)

      objects.forEach { object ->
         val image = objectImage(object)
         canvas.drawBitmap(image, ...)
      }
   }
   
   private fun objectImage(object: Object): Bitmap {
      val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
      val canvas = Canvas(bitmap)

      // Draw object on canvas

      return bitmap
   }
}

I would like to see if there is a more memory efficient way to create bitmaps in the objectImage function as I will be iterating of many objects to draw the tile. When I hit a certain threshold for objects my app crashes with an OutOfMemoryException.

I have looked at creating the Bitmap with BitmapFactory, however it looks like all the methods point to a file or stream. I might be able to roll my own bitmap pool, but it would have to be thread safe as TileProvider is not thread safe. However not sure that is where my issue is.

1

There are 1 answers

4
user496854 On

have you tried re-sizing the bitmap before you send it to the canvas?

// I'm picking a randomly small tile size, but you can adjust it as you need
val size = 36
val scaledBitmap = Bitmap.createScaledBitmap(origBitmap, size, size, true)