Reputation: 1870
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.
Upvotes: 7
Views: 5603
Reputation: 2172
For circular images using Picasso, use this class that implements Transformation.
Picasso.with(context).load(url).transform(new RoundedTransformation(radius, margin)).into(imageview);
Upvotes: 14
Reputation: 76075
When doing this with Picasso you should either:
Transformation
so that the rounded bitmap is cached in memory, orImageView
subclass. Details on this technique were outlined by the ragin' cagin' Romain Guy on his blogTrying to pull the underlying Bitmap
out of an ImageView
is an anti-pattern. If you do need access to a Bitmap
(and you don't, you should use one of the above), implement Target
on your view whose onBitmapSuccess
callback will provide it.
Upvotes: 5