How to merge two bitmaps (overlap)

Issue

I’m trying to merge two Bitmap. I have a resource on my Drawable and I get the Bitmap as :

val defaultBitmap = AppCompatResources.getDrawable(context, R.drawable.default_image)!!.toBitmap()

Then I have another but comes from an url and then I convert it to Bitmap

Glide.with(requireContext())
 .asBitmap()
 .load("url")
 .override(32,32)
 .into(object: CustomTarget<Bitmap>() {
    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
       //whatever
    }

    override fun onLoadCleared(placeholder: Drawable?) { }
 }
)

And then the way I’m trying to merge is :

val defaultBitmap = AppCompatResources.getDrawable(context, R.drawable.default_image)!!.toBitmap()
val resultBitmap = Bitmap.createBitmap(defaultBitmap.width, defaultBitmap.height, defaultBitmap.config)
val twiseImage = Canvas(resultBitmap)
twiseImage.drawBitmap(defaultBitmap, Matrix(), null)
twiseImage.drawBitmap(bitmapGlide, 0f,0f,null)

The thing is that I’d like to end up is :

enter image description here

Number 1 is the default one and the Number 2 is the glide one, I want to be in the center of the Number 1.

Solution

Try using drawBitmap (bitmap, left, top, paint):

val defaultBitmap = AppCompatResources.getDrawable(context, R.drawable.default_image)!!.toBitmap()
val resultBitmap = Bitmap.createBitmap(defaultBitmap.width, defaultBitmap.height, defaultBitmap.config)
val twiseImage = Canvas(resultBitmap)
val x = (defaultBitmap.width - bitmapGlide.width) / 2
val y = (defaultBitmap.height - bitmapGlide.height) / 2
twiseImage.drawBitmap(bitmapGlide, x, y, null)

You could also translate the canvas by (x,y) and draw at the (0,0) coordinates.

Answered By – Cheticamp

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published