Created
March 2, 2016 09:03
-
-
Save pskink/375e68ebe0a28e9103bc to your computer and use it in GitHub Desktop.
This file contains 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
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