自定义 ImageView 类不适用于 Picasso 图像下载库

2024-02-10

我最近从 ImageView 扩展创建了 CircularImageView 类,该类使图像成为带有彩色边框的圆形。这是通过 onDraw(canvas) 方法通过在传入的画布上绘图来完成的:

//load the bitmap
    loadBitmap();

    // init shader
    if(image !=null)
    {   
        shader = new BitmapShader(Bitmap.createScaledBitmap(image, viewWidth + (borderWidth * 2), viewHeight + (borderWidth * 2), true), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        paint.setShader(shader);

        int circleCenter = viewWidth / 2;

        // circleCenter is the x or y of the view's center
        // radius is the radius in pixels of the cirle to be drawn
        // paint contains the shader that will texture the shape
        canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth, paintBorder);
        canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter, paintBackground);
        canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter, paint);
    }   

因此,当通过可绘制对象或位图设置图像时,该位有效。我还扩展了它,这样我就可以将它与 Google 的 Volley NetworkImageView 一起使用,它也可以工作。

当我尝试将 CircularImageView 类与 Picasso 图像下载库一起使用时,我的问题就出现了,因为我正在将其视为 Volley 的替代品。获取 BitmapDrawable 时,第一行的 loadBitmap() 函数中会发生 ClassCastException。

private void loadBitmap()
{
    BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();

    if(bitmapDrawable != null)
        image = bitmapDrawable.getBitmap();
}

最初,在毕加索下载图片之前,它会很好地围绕占位符图像。但是,一旦 Picasso 下载了图像,它就会失败并出现 ClassCastException,因为 getDrawable() 返回并且是 PicassoDrawable 而不是 BitmapDrawable。

我想继续在 CircularImageView 类中的 onDraw(canvas) 方法中完成对图像进行舍入的工作,因为它很好地包含并且是自动的,而不是每次使用 Picasso 设置 ImageView 时都执行此过程。这可能吗?

提前致谢。


对于使用 Picasso 的圆形图像,请使用this https://gist.github.com/aprock/6213395实现转换的类。

Picasso.with(context).load(url).transform(new RoundedTransformation(radius, margin)).into(imageview);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自定义 ImageView 类不适用于 Picasso 图像下载库 的相关文章