皮卡索库:为占位符实现圆角

4

使用Picasso.with(activity).load(url).transform(new CircleTransform(22,12)).into(imageView);我们可以为加载图片设置圆角。但是占位符和错误图片没有圆角?

我参考的链接Make ImageView with Round Corner Using picasso


使用Glide,您可以轻松完成这个任务。 - jigar savaliya
2个回答

7
 Picasso.with(getApplicationContext()).load(url).placeholder(setCircularImage(R.drawable.profile_sample)).error(setCircularImage(R.drawable.profile_sample)).transform(new CircleTransform()).into(ivMenuProfile);

添加setCircularImage方法,带有占位符,用于将占位符放入圆形视图中。
private RoundedBitmapDrawable setCircularImage(int id) {
        Resources res = getApplicationContext().getResources();
        Bitmap src = BitmapFactory.decodeResource(res, id);
        RoundedBitmapDrawable roundedBitmapDrawable = 
        RoundedBitmapDrawableFactory.create(res, src);
        roundedBitmapDrawable.setCornerRadius(Math.max(src.getWidth(), src.getHeight()) / 2.0f);
        return roundedBitmapDrawable;
    }

添加CircleTransform()函数,用于将加载的Url图片转换为圆形。

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";
    }
}

3
这在Picasso中不可行。请参见这里的答案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接