Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom ImageView class not working with Picasso image downloading library

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.

like image 281
Richard Lewin Avatar asked Oct 23 '13 00:10

Richard Lewin


1 Answers

For circular images using Picasso, use this class that implements Transformation.

Picasso.with(context).load(url).transform(new RoundedTransformation(radius, margin)).into(imageview);
like image 98
droidx Avatar answered Oct 19 '22 23:10

droidx