After stucking few days on that problem I just wanted to share my solution with you and save your time.
Problem
1. Download an image from any URL
2. Show it as a circular image (if download succeeded)
3. Or show a default image in the same ImageView
(if download failed)
[EDIT]
I removed my answer because of very useful hints coming from @Budius and the better working solution which he offers below
Best way to achieve the task from the question is using Picasso with a circular transformation.
Like the following code:
Picasso
.with(context)
.load(url)
.placeholder(placeHolderDrawable)
.error(errorDrawable)
.transform(circleTransform)
.into(imageView);
and the code for the circleTransform
copied from this link: https://gist.github.com/julianshen/5829333
public class CircleTransform implements Transformation {
@Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size/2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
@Override
public String key() {
return "circle";
}
}
compile 'com.squareup.picasso:picasso:2.5.0'//for load image from URL
compile 'de.hdodenhof:circleimageview:1.3.0'//for circle imageview
//add view in xml file
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/ivProfileImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:contentDescription="@null"
app:border_color="#ffffff"
app:border_width="2dp" />
//Load image from Java file
private CircleImageView mIvProfileImage;
mIvProfileImage = (CircleImageView) findViewById(R.id.ivProfileImage);
Picasso.with(getApplicationContext()).load("IMAGE URL")//download URL
.placeholder(R.drawable.ic_user_class)//use defaul image
.error(R.drawable.ic_user_class)//if failed
.into(mIvProfileImage);//imageview