Create Circle ImageView with Picasso

Here is how to create circle ImageView and load the image with picasso library.
First of all you need to create transformation subclass to create circle shape following below.

     /**
     * Enables hardware accelerated rounded corners.
     * original idea here : http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/
     */
    public class RoundedTransformation implements com.squareup.picasso.Transformation {
        private final int radius;
        private final int margin;  // dp

        // radius is corner radii in dp
        // margin is the board in dp
        public RoundedTransformation(final int radius, final int margin) {
            this.radius = radius;
            this.margin = margin;
        }

        @Override
        public Bitmap transform(final Bitmap source) {
            final Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));

            Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() - margin, source.getHeight() - margin), radius, radius, paint);

            if (source != output) {
                source.recycle();
            }

            return output;
        }

        @Override
        public String key() {
            return "rounded";
        }
    }

After that, what you need to do just load your image with transformation class above.

Picasso.with(yourContext)
       .load("...") // Your image source.
       .transform(new RoundedTransformation(50, 4))
       .fit()  // Fix centerCrop issue: http://stackoverflow.com/a/20824141/1936697
       .centerCrop()
       .into(yourImageView);

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s