I have recently extended from an ImageView to create a CircularImageView class which makes the image circular with a coloured border. This is done via the onDraw(canvas) method by drawing onto the canvas that is passed in:
//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);
}
So this bit works when setting the image via a drawable or bitmap. I have also extended it so I can use it with Google's Volley NetworkImageView which also works.
My problem comes when I try and us my CircularImageView class alongside Picasso image downloading library as I am looking at it as an alternative to Volley. What occurs is a ClassCastException in my loadBitmap() function on the first line when getting the BitmapDrawable.
private void loadBitmap()
{
BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();
if(bitmapDrawable != null)
image = bitmapDrawable.getBitmap();
}
Initally before Picasso has downloaded the picture it rounds the placeholder image just fine. But as soon as the image has been downloaded by Picasso it fails with a ClassCastException as getDrawable() returns and PicassoDrawable rather than a BitmapDrawable.
I would like to keep the work to round the image in the onDraw(canvas) method in my CircularImageView class as it is nicely contained and automatic as opposed to doing the process when setting up the ImageView with Picasso each and every time. Is this possible?
Thanks in advance.
For circular images using Picasso, use this class that implements Transformation.
Picasso.with(context).load(url).transform(new RoundedTransformation(radius, margin)).into(imageview);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With