Search code examples
androidkotlinandroid-drawableondraw

Custom Drawable not drawn


I am trying to create a custom Drawable that converts a square image into a round one. The image is transformed but not drawn.

I can see that if I return the RoundedBitmapDrawable in a separate function, it is shown in the ImageView but if I expect the overridden function draw to do the job, I don'see anything

My class

class RoundImage(context: Context?, bitmap: Bitmap): Drawable() {

    private var dr: RoundedBitmapDrawable

    init {
        // give a round shape
        dr = RoundedBitmapDrawableFactory.create(context!!.resources, bitmap)
        dr.isCircular = true
        dr.cornerRadius = bitmap.width / 2.0f
    }

    override fun draw(canvas: Canvas) {
        // this draws nothing
        dr.draw(canvas)
    }

    override fun setAlpha(alpha: Int) {
        
    }

    override fun setColorFilter(colorFilter: ColorFilter?) {
        
    }

    override fun getOpacity(): Int {
        
    }


    /**
     * This returns a round drawable
     */
    fun getDrawable(): Drawable {
        return dr
    }
}

I try to show it with

val roundImage = RoundImage(context, bitmap)
myPicture.setImageDrawable(roundImage)

Solution

  • You need also override onBoundsChange method like this:

    override fun onBoundsChange(bounds: Rect) {
        dr.bounds = bounds
    }
    

    Alternatively, using DrawableWrapper might be a better option.

    class RoundImage(context: Context, bitmap: Bitmap) : DrawableWrapper(null) {
    
        init {
            // give a round shape
            val dr = RoundedBitmapDrawableFactory.create(context.resources, bitmap)
            dr.isCircular = true
            this.drawable = dr
        }
    
    }