自定义的ImageView类无法与Picasso图片下载库一起使用

7

我最近扩展了一个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);
    }   

当使用drawable或bitmap设置图像时,这段代码起作用。我还将其扩展,以便可以与Google的Volley NetworkImageView一起使用,这也可以正常工作。

但是当我尝试将我的CircularImageView类与Picasso图像下载库一起使用时,出现了问题。我正在考虑它作为Volley的替代方案。在loadBitmap()函数的第一行获取BitmapDrawable时,会出现ClassCastException。

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

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

最初在 Picasso 下载图片之前,它可以很好地将占位符图像转换为圆形。但是一旦 Picasso 下载了图像,由于 getDrawable() 返回的是 PicassoDrawable 而不是 BitmapDrawable,因此会导致 ClassCastException 错误。

我想保留 CircularImageView 类中 onDraw(canvas) 方法中的图像圆形处理工作,因为这样做更容易管理和自动化,而不是每次使用 Picasso 设置 ImageView 时都进行处理。这种方式可行吗?

谢谢您的帮助。

2个回答

14

要使用 Picasso 制作圆形图片,请使用实现转换的 此类

Picasso.with(context).load(url).transform(new RoundedTransformation(radius, margin)).into(imageview);

这会每次都创建一个新的位图,是吗? - secureboot
感谢DesertIvy、droidx和Jake Wharton的帮助。这个项目已经被搁置了,现在才回到这个问题上来。我刚刚尝试了上面的方法,完美地解决了问题。 - Richard Lewin

5
当使用Picasso时,您应该执行以下操作之一:
  1. 将圆角应用为“转换”,以便在内存中缓存圆角位图,或者
  2. 在自定义的ImageView子类中使用着色器夹紧画布。有关此技术的详细信息已在ragin' cagin' Romain Guy的博客中概述。
试图从ImageView中提取基础Bitmap是一种反模式。如果您确实需要访问Bitmap(而且您不需要,应该使用上述方法之一),请在视图上实现Target,其onBitmapSuccess回调将提供它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接