* Returns a bitmap with the desired width and height. * The actual returned bitmap size might be smaller than the requested size. */
| 89 | * The actual returned bitmap size might be smaller than the requested size. |
| 90 | */ |
| 91 | fun get(desiredWidth: Int, desiredHeight: Int): BitmapHandler? { |
| 92 | if (desiredWidth == 0 || desiredHeight == 0) { |
| 93 | return null |
| 94 | } |
| 95 | |
| 96 | val resolvedWidth: Int |
| 97 | val resolvedHeight: Int |
| 98 | |
| 99 | if (desiredWidth <= maxWidth && desiredHeight <= maxHeight) { |
| 100 | resolvedWidth = desiredWidth |
| 101 | resolvedHeight = desiredHeight |
| 102 | } else { |
| 103 | val desiredWidthF = desiredWidth.toFloat() |
| 104 | val desiredHeightF = desiredHeight.toFloat() |
| 105 | |
| 106 | val xRatio = desiredWidthF / maxWidth.toFloat() |
| 107 | val yRatio = desiredHeightF / maxHeight.toFloat() |
| 108 | val ratio = max(xRatio, yRatio) |
| 109 | |
| 110 | resolvedWidth = (desiredWidthF / ratio).roundToInt() |
| 111 | resolvedHeight = (desiredHeightF / ratio).roundToInt() |
| 112 | } |
| 113 | |
| 114 | var resolvedCachedBitmap: CachedBitmap? = null |
| 115 | |
| 116 | synchronized(cachedBitmaps) { |
| 117 | val it = cachedBitmaps.iterator() |
| 118 | while (it.hasNext()) { |
| 119 | val cachedBitmap = it.next() |
| 120 | |
| 121 | // TODO(simon): We could leverage reconfigure() to allow re-using buffers which are |
| 122 | // bigger than the requested size. |
| 123 | if (cachedBitmap.getBitmap().width == resolvedWidth && cachedBitmap.getBitmap().height == resolvedHeight) { |
| 124 | cachedBitmap.retain() |
| 125 | |
| 126 | it.remove() |
| 127 | |
| 128 | resolvedCachedBitmap = cachedBitmap |
| 129 | |
| 130 | break |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | if (resolvedCachedBitmap != null) { |
| 136 | resolvedCachedBitmap!!.prepareForReuse() |
| 137 | return resolvedCachedBitmap |
| 138 | } |
| 139 | |
| 140 | return try { |
| 141 | // logger.info("Allocating bitmap of size ${resolvedWidth}x${resolvedHeight}") |
| 142 | val bitmap = Bitmap.createBitmap(resolvedWidth, resolvedHeight, bitmapConfig) ?: return null |
| 143 | CachedBitmap(this, bitmap) |
| 144 | } catch (exc: OutOfMemoryError) { |
| 145 | logger.error("Failed to allocate bitmap of size ${resolvedWidth}x${resolvedHeight}: ${exc.message}") |
| 146 | null |
| 147 | } |
| 148 | } |
nothing calls this directly
no test coverage detected