Created
July 8, 2017 13:39
-
-
Save Nikaoto/23516110cf1e75f1b53f08d7dbd9324c to your computer and use it in GitHub Desktop.
A custom Tranformation for picasso which takes a rectangular drawable and its width & height and returns a circular one. Scales smoothly to the view size.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import android.graphics.Bitmap; | |
import android.graphics.BitmapShader; | |
import android.graphics.Canvas; | |
import android.graphics.Matrix; | |
import android.graphics.Paint; | |
import com.squareup.picasso.Transformation; | |
public class CircleTransformation implements Transformation { | |
private int viewSize, viewHeight, viewWidth; | |
public CircleTransformation(int width, int height) { | |
this.viewWidth = width; | |
this.viewHeight = height; | |
this.viewSize = Math.min(width, height); | |
} | |
@Override public Bitmap transform(Bitmap source) { | |
Bitmap scaledSource; | |
if (source.getWidth() != viewWidth && source.getHeight() != viewHeight) { | |
scaledSource = Bitmap.createScaledBitmap(source, viewWidth, viewHeight, true); | |
} else { | |
scaledSource = source; | |
} | |
Bitmap bitmap = Bitmap.createBitmap(viewSize, viewSize, Bitmap.Config.ARGB_8888); | |
int sourceSize = Math.min(scaledSource.getWidth(), scaledSource.getHeight()); | |
int width = (scaledSource.getWidth() - sourceSize) / 2; | |
int height = (scaledSource.getHeight() - sourceSize) / 2; | |
/* | |
int sourceSize = Math.min(viewWidth, viewHeight); | |
int width = (viewWidth - sourceSize) / 2; | |
int height = (viewHeight - sourceSize) / 2; | |
*/ | |
Canvas canvas = new Canvas(bitmap); | |
Paint paint = new Paint(); | |
BitmapShader shader = | |
new BitmapShader(scaledSource, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); | |
if (width != 0 || height != 0) { | |
// source isn't square, move viewport to center | |
Matrix matrix = new Matrix(); | |
matrix.setTranslate(-width, -height); | |
shader.setLocalMatrix(matrix); | |
} | |
paint.setShader(shader); | |
paint.setAntiAlias(true); | |
float r = viewSize / 2f; | |
canvas.drawCircle(r, r, r, paint); | |
scaledSource.recycle(); | |
source.recycle(); | |
return bitmap; | |
} | |
@Override public String key() { | |
return "CropCircleTransformation()"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment