Android: padding left a bitmap with white color

Viewed 13544

How to set all white the 10 rows on the left side of a Bitmap? I'v got a Bitmap that has to be padded on the left side. I thought i can create a new image iterate on the old one getpixel for each position and setpixel on the new one (white or colored) than return the new bitmap...is this wrong? Any suggestion? thanks a lot!

5 Answers

Here's a kotlin extension function with RxJava to get it done. I haven't tested completely but based combined the previous answers to get something

fun Bitmap.pad(top: Float = 0F, bottom: Float = 0F, left: Float = 0F, right: Float = 0F): Single<Bitmap> {
    return Single.create<Bitmap> { emitter ->
        val output = Bitmap.createBitmap(
            (width + left + right).toInt(),
            (height + top + bottom).toInt(),
            Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(output)

        canvas.drawBitmap(this, left, top, null)

        emitter.onSuccess(output)
    }.subscribeOn(Schedulers.computation())
}

I think the coroutine version would simply be

suspend fun Bitmap.pad(top: Float = 0F, bottom: Float = 0F, left: Float = 0F, right: Float = 0F): Bitmap {
    val output = Bitmap.createBitmap(
        (width + left + right).toInt(),
        (height + top + bottom).toInt(),
        Bitmap.Config.ARGB_8888
    )
    val canvas = Canvas(output)

    canvas.drawBitmap(this, left, top, null)

    return output
}

I just did this to give padding from all side. Hope it will help someone. Combination of https://stackoverflow.com/a/44060669/6480433 & https://stackoverflow.com/a/6957333/6480433 these answer.

Bitmap outputimage = Bitmap.createBitmap(Src.getWidth() + padding_x,Src.getHeight() + padding_y, Bitmap.Config.ARGB_8888);
        Canvas can = new Canvas(outputimage);
        can.drawBitmap(Src, padding_x, padding_y, null);

        Bitmap output = Bitmap.createBitmap(outputimage.getWidth()+padding_x, outputimage.getHeight() + padding_y, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        canvas.drawBitmap(outputimage, 0, 0, null);    
  return output;
Related