我最近从
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,paintBorder);
canvas.drawCircle(circleCenter + borderWidth,circleCenter,paintBackground);
canvas.drawCircle(circleCenter + borderWidth,paint);
}
因此,当通过drawable或bitmap设置图像时,此位有效.我也扩展了它,所以我可以使用谷歌的Volley NetworkImageView,它也可以使用.
当我尝试将我的CircularImageView类与Picasso图像下载库一起使用时,我的问题出现了,因为我将它视为Volley的替代品.在获取BitmapDrawable时,在第一行的loadBitmap()函数中发生了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时的过程.这可能吗?
提前致谢.
解决方法
对于使用Picasso的圆形图像,请使用实现Transformation的
this类.
Picasso.with(context).load(url).transform(new RoundedTransformation(radius,margin)).into(imageview);