自定义ImageView类不与Picasso图像下载库一起使用

Ric*_*win 7 android image bitmapimage android-canvas picasso

我最近从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);
    }   
Run Code Online (Sandbox Code Playgroud)

因此,当通过drawable或bitmap设置图像时,此位有效.我也扩展了它,所以我可以使用谷歌的Volley NetworkImageView,它也可以使用.

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

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

    if(bitmapDrawable != null)
        image = bitmapDrawable.getBitmap();
}
Run Code Online (Sandbox Code Playgroud)

最初在毕加索下载图片之前,它将占位符图像四舍五入.但是一旦Picasso下载了图像,它就会因为getDrawable()返回和PicassoDrawable而不是BitmapDrawable而失败并出现ClassCastException.

我想保持工作在我的CircularImageView类中的onDraw(canvas)方法中舍入图像,因为它很好地包含和自动,而不是每次都用Picasso设置ImageView时的过程.这可能吗?

提前致谢.

dro*_*idx 14

对于使用Picasso的圆形图像,请使用此类实现Transformation.

Picasso.with(context).load(url).transform(new RoundedTransformation(radius, margin)).into(imageview);
Run Code Online (Sandbox Code Playgroud)


Jak*_*ton 5

与毕加索合作时,您应该:

  1. 将舍入应用为Transformation圆形位图缓存在内存中,或
  2. 在自定义ImageView子类中使用着色器夹住画布.有关这项技术的详细信息由ragin'cagin'Romain Guy 在他的博客上概述

试图将底层拉Bitmap出来ImageView是一种反模式.如果您确实需要访问Bitmap(并且您不需要,请使用上述之一),请Target在您的onBitmapSuccess回调将提供它的视图上实现.