Skip to content

Instantly share code, notes, and snippets.

@guffyWave
Forked from donnfelker/CircularTransformation.java
Last active August 29, 2015 14:24
Show Gist options
  • Save guffyWave/b032ab5486f9d03eecbe to your computer and use it in GitHub Desktop.
Save guffyWave/b032ab5486f9d03eecbe to your computer and use it in GitHub Desktop.
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment