Skip to content

Instantly share code, notes, and snippets.

@justasm
Created August 15, 2016 19:34
Show Gist options
  • Save justasm/b70ef9bf5c17c38568f61183ba9ad8ad to your computer and use it in GitHub Desktop.
Save justasm/b70ef9bf5c17c38568f61183ba9ad8ad to your computer and use it in GitHub Desktop.
Picasso CircleTransformation
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import com.squareup.picasso.Transformation;
public class CircleTransformation implements Transformation {
@Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int left = (source.getWidth() - size) / 2;
int top = (source.getHeight() - size) / 2;
final Paint paint = new Paint();
BitmapShader shader = new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
if (left != 0 || top != 0) {
// center source
Matrix translateTransform = new Matrix();
translateTransform.setTranslate(-left, -top);
shader.setLocalMatrix(translateTransform);
}
paint.setShader(shader);
paint.setAntiAlias(true);
Bitmap result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
float radius = size / 2f;
canvas.drawCircle(radius, radius, radius, paint);
source.recycle();
return result;
}
@Override
public String key() {
return CircleTransformation.class.getName();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment