我最近扩展了一个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 时都进行处理。这种方式可行吗?
谢谢您的帮助。