Skip to content

Instantly share code, notes, and snippets.

@Sefford
Created May 22, 2014 19:46
Show Gist options
  • Save Sefford/d24b5932813f1230de79 to your computer and use it in GitHub Desktop.
Save Sefford/d24b5932813f1230de79 to your computer and use it in GitHub Desktop.
Picasso transformation to achieve a circular crop of an image
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import com.squareup.picasso.Transformation;
/**
* Applies the same transformation in CircularImageView but only once to the downloaded bitmap from the Network.
* <p/>
*
* @author Saul Diaz <sefford@gmail.com>
*/
public class CircularTransformation implements Transformation {
/**
* Size of the target bitmap to generate a squared image
*/
private final int size;
/**
* Radius of the image
*/
private final int radius;
/**
* Creates a new Circular Transformation. It takes a size to properly produce a rounded image minimizing the jagged edges
*
* @param size Size of the transformation
*/
public CircularTransformation(int size) {
this.size = size;
this.radius = (int) Math.ceil(size / 2);
}
@Override
public Bitmap transform(Bitmap source) {
Bitmap output = Bitmap.createBitmap(size,
size, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, source.getWidth(),
source.getHeight());
final Rect target = new Rect(0, 0, size, size);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(radius, radius, radius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, rect, target, paint);
source.recycle();
return output;
}
@Override
public String key() {
return "radius" + size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment