Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Picasso and CircularTransform Example
import android.graphics.*;
import com.squareup.picasso.Transformation;
/**
* Transforms an image into a circle representation. Such as a avatar.
*/
public class CircularTransformation implements Transformation
{
int radius = 10;
public CircularTransformation(final int radius)
{
this.radius = radius;
}
public CircularTransformation()
{
}
@Override
public Bitmap transform(final Bitmap source)
{
Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, source.getWidth(), source.getHeight());
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(source.getWidth() / 2 + 0.7f, source.getHeight() / 2 + 0.7f, source.getWidth() / 2 - 1.1f, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, rect, rect, paint);
if(source != output) {
source.recycle();
}
return output;
}
@Override
public String key()
{
return "circular" + String.valueOf(radius);
}
}
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
// all other init code
ImageView avatar = findViewById(R.id.avatar);
Picasso.with(this)
.load("http://i.imgur.com/DvpvklR.png")
.transform(new CircularTransformation(10)) // 10 is the radius
.into(avatar);
// Do the happy dance
}
}
@felipecsl
Copy link

felipecsl commented Oct 8, 2014

this is what I've been using:

public class CircleTransformation implements Transformation {


    public CircleTransformation() {
    }

    @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));

        final Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Config.ARGB_8888);
        final Canvas canvas = new Canvas(output);
        canvas.drawCircle(source.getWidth() / 2, source.getHeight() / 2, source.getWidth() / 2, paint);

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

        return output;
    }

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

@premnirmal
Copy link

premnirmal commented Oct 13, 2014

Nice work! can we see an example?

@tasomaniac
Copy link

tasomaniac commented Oct 15, 2014

Nice work. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment