在坚持这个问题几天之后,我只想和你分享我的解决方案并节省你的时间。
问题
1.从任何URL下载图像
2.将其显示为圆形图像(如果下载成功)
3.或者在同一ImageView
中显示默认图像(如果下载失败)
[编辑] 我删除了我的答案,因为来自@Budius的非常有用的提示以及他在下面提供的更好的工作解决方案
答案 0 :(得分:1)
从问题中完成任务的最佳方法是使用Picasso进行循环转换。
与以下代码类似:
Picasso
.with(context)
.load(url)
.placeholder(placeHolderDrawable)
.error(errorDrawable)
.transform(circleTransform)
.into(imageView);
以及从此链接复制的circleTransform
代码: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";
}
}
答案 1 :(得分:0)
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