自定义可绘制未绘制

问题描述

我正在尝试创建一个自定义Drawable,它将方形图像转换为圆形图像。图片已变形但未绘制。

我可以看到,如果我在一个单独的函数中返回RoundedBitmapDrawable,它会显示在ImageView中,但是如果我希望重写的函数draw能够完成任务,我不会'看到任何东西

我的课

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
    }
}

我尝试用

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

解决方法

您还需要像这样重写onBoundsChange方法:

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

或者,使用DrawableWrapper可能是更好的选择。

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
    }

}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...