Home > Software design >  How to fill with color only the icon on canvas,without the background android studio
How to fill with color only the icon on canvas,without the background android studio

Time:12-02

I want to change the color of my png,i want to fill it with color,so i thought about creating a bitmap from the png,placing it on a canvas and drawing the canvas,but it is drawing the whole canvas,like this,so my icons are covered completely

enter image description here

This is my code:

private fun testResizeImg(imgRes: Int): BitmapDescriptor {
        var bm = BitmapFactory.decodeResource(resources, imgRes)
        bm = Bitmap.createScaledBitmap(bm, (bm.width * 0.1).toInt(), (bm.height * 0.1).toInt(), true)
        val canvas = Canvas(bm)
        val paint = Paint()
        paint.color = Color.BLUE
        canvas.drawPaint(paint)
        return BitmapDescriptorFactory.fromBitmap(bm)
    }

What is the best approach to do this,i have a png and i want to paint it.

CodePudding user response:

You can try something like that ? (not tested)

You can use theColor Filter to change the icon's color at runtime.

Then you transform the drawable into Bitmap.

    private fun testResizeImg(@DrawableRes imgRes: Int): BitmapDescriptor {
        val mIcon = ContextCompat.getDrawable(getActivity(), imgRes)
        mIcon?.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(Color.BLUE, BlendModeCompat.SRC_ATOP)
        var bm : Bitmap = (mIcon as BitmapDrawable).bitmap
        bm = Bitmap.createScaledBitmap(bm, (bm.width * 0.1).toInt(), (bm.height * 0.1).toInt(), true)
        return BitmapDescriptorFactory.fromBitmap(bm)
    }

Note that the @DrawableRes is here to help for the code inspection

CodePudding user response:

private fun testResizeImg(imgRes: Int): BitmapDescriptor {
        var bm = BitmapFactory.decodeResource(resources, imgRes)
        bm = Bitmap.createScaledBitmap(bm, (bm.width * 0.1).toInt(), (bm.height * 0.1).toInt(), true)
        val canvas = Canvas(bm)
        canvas.drawBitmap(bm,0F,0F,null)
        return BitmapDescriptorFactory.fromBitmap(bm)
    }
  • Related