使用毕加索创建圆形图像

时间:2017-09-21 09:57:19

标签: android imageview transform picasso

我想从网址加载profilr图片图片,并从资源中使用Picasso库将其设为圆形。我喜欢,

dependencies {
    compile 'com.squareup.picasso:picasso:2.4.0'
}

从资源加载图片(R.drawable.profile_sample),

Picasso.with(getApplicationContext()).load(R.drawable.profile_sample).placeholder(setCircularImage(R.drawable.profile_sample)).into(imageView_ProfilePic);

也来自网址,

Picasso.with(getApplicationContext()).load("http://shidhints.com").placeholder(setCircularImage(R.drawable.profile_sample)).into(imageView_ProfilePic);

另外,我使用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;
    }

1 个答案:

答案 0 :(得分:2)

我已经创建了一个类CircleTransform.java来使图像循环并修改代码以从中加载图像,

Picasso.with(getApplicationContext()).load(R.drawable.profile_sample).placeholder(setCircularImage(R.drawable.profile_sample)).transform(new CircleTransform()).into(imageView_ProfilePic);

也来自网址,

Picasso.with(getApplicationContext()).load("http://shidhints.com").placeholder(setCircularImage(R.drawable.profile_sample)).transform(new CircleTransform()).into(imageView_ProfilePic);

<强> CircleTransform.java

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