【问题标题】:Custom ImageView class not working with Picasso image downloading library自定义 ImageView 类不适用于毕加索图像下载库
【发布时间】:2013-12-08 03:24:48
【问题描述】:

我最近从 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 时执行该过程。这可能吗?

提前致谢。

【问题讨论】:

    标签: android image android-canvas bitmapimage picasso


    【解决方案1】:

    对于使用毕加索的圆形图像,请使用实现转换的this 类。

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

    【讨论】:

    • 这每次都会创建一个新的位图,不是吗?
    • 感谢 DesertIvy、droidx 和 Jake Wharton 的帮助。这个项目被搁置了,现在才回到问题上来。我刚刚尝试了上述方法,效果非常完美。
    【解决方案2】:

    在使用毕加索时,您应该:

    1. 将舍入应用为Transformation,以便将舍入位图缓存在内存中,或者
    2. 在自定义ImageView 子类中使用着色器夹住画布。该技术的详细信息由 ragin' cagin' Romain Guy on his blog 概述

    试图从ImageView 中提取底层Bitmap 是一种反模式。如果您确实需要访问 Bitmap(而您不需要,您应该使用上述之一),请在您的视图上实现 Target,其 onBitmapSuccess 回调将提供它。

    【讨论】:

      猜你喜欢
      • 2018-12-17
      • 2016-05-11
      • 2015-05-09
      • 2021-08-09
      • 2020-05-02
      • 2014-09-18
      • 2019-07-15
      • 2014-09-02
      • 2014-08-29
      相关资源
      最近更新 更多