Skip to content

Instantly share code, notes, and snippets.

@Folyd
Created March 11, 2016 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Folyd/47771a840e183d212eca to your computer and use it in GitHub Desktop.
Save Folyd/47771a840e183d212eca to your computer and use it in GitHub Desktop.
Text badge drawable
public class TextBadgeDrawable extends Drawable {
private Paint mPaint;
private Rect mBounds;
private Rect mTextBounds;
private RectF mRectF;
private int mColor;
private String mText;
public TextBadgeDrawable() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBounds = new Rect();
mTextBounds = new Rect();
mRectF = new RectF();
setBounds(0, 0, 60, 40);
}
public void setConfiguration(String text, int color) {
mText = text;
mColor = color;
}
@Override
public void draw(Canvas canvas) {
mBounds = getBounds();
//Do not use canvas.getClipBounds(),due to canvas delivered from parent container view.
//canvas.getClipBounds(mBounds);
canvas.drawColor(Color.TRANSPARENT);
mPaint.setColor(mColor);
mPaint.setTextSize(28f);
//Draw text center,refer to http://chris.banes.me/2014/03/27/measuring-text/
mPaint.getTextBounds(mText, 0, mText.length(), mTextBounds);
float textHeight = mTextBounds.height();
float textWidth = mPaint.measureText(mText);
canvas.drawText(mText, mBounds.centerX() - textWidth / 2f, mBounds.centerY() + textHeight / 2f, mPaint);
mPaint.setStrokeWidth(3f);
mPaint.setStyle(Paint.Style.STROKE);
mRectF.left = mBounds.left;
mRectF.top = mBounds.top;
mRectF.right = mBounds.right;
mRectF.bottom = mBounds.bottom;
canvas.drawRoundRect(mRectF, 8f, 8f, mPaint);
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
mPaint.setColorFilter(colorFilter);
invalidateSelf();
}
@Override
public int getOpacity() {
// not sure, so be safe
return PixelFormat.TRANSLUCENT;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment