Skip to content

Instantly share code, notes, and snippets.

@pskink
Created March 2, 2016 09:03
Show Gist options
  • Save pskink/375e68ebe0a28e9103bc to your computer and use it in GitHub Desktop.
Save pskink/375e68ebe0a28e9103bc to your computer and use it in GitHub Desktop.
class CircleBitmapDrawable extends Drawable {
Bitmap bitmap;
Paint maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint borderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
float side;
float radius;
public CircleBitmapDrawable(Bitmap wrappedBitmap, float borderWidth, int borderColor) {
bitmap = wrappedBitmap;
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setStrokeWidth(borderWidth);
borderPaint.setColor(borderColor);
side = Math.min(bitmap.getWidth(), bitmap.getHeight());
}
@Override
protected void onBoundsChange(Rect bounds) {
Matrix matrix = new Matrix();
RectF src = new RectF(0, 0, side, side);
src.offset((bitmap.getWidth() - side) / 2, (bitmap.getHeight() - side) / 2);
RectF dst = new RectF(bounds);
dst.inset(borderPaint.getStrokeWidth(), borderPaint.getStrokeWidth());
matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
Shader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
shader.setLocalMatrix(matrix);
maskPaint.setShader(shader);
matrix.mapRect(src);
radius = src.width() / 2;
}
@Override
public void draw(Canvas canvas) {
Rect b = getBounds();
canvas.drawCircle(b.exactCenterX(), b.exactCenterY(), radius, maskPaint);
canvas.drawCircle(b.exactCenterX(), b.exactCenterY(), radius + borderPaint.getStrokeWidth() / 2, borderPaint);
}
@Override public void setAlpha(int alpha) {}
@Override public void setColorFilter(ColorFilter cf) {}
@Override public int getOpacity() {return PixelFormat.TRANSLUCENT;}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment