Last active
June 7, 2021 11:17
-
-
Save darnmason/8591eb817233641cc66adbbd7f25c4eb to your computer and use it in GitHub Desktop.
A span with a circle background and different color text, intended for one or 2 characters as more will affect the height of the span
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
import android.graphics.Canvas; | |
import android.graphics.Paint; | |
import android.support.annotation.NonNull; | |
import android.support.annotation.Nullable; | |
import android.text.style.ReplacementSpan; | |
public class CircleTextSpan extends ReplacementSpan { | |
private final int backgroundColor; | |
private final int textColor; | |
private final int padding; | |
public CircleTextSpan(int backgroundColor, int textColor, int padding) { | |
this.backgroundColor = backgroundColor; | |
this.textColor = textColor; | |
this.padding = padding; | |
} | |
@Override | |
public int getSize(@NonNull Paint paint, | |
CharSequence text, | |
int start, | |
int end, | |
@Nullable Paint.FontMetricsInt fontMetricsInt | |
) { | |
return Math.round(measureWidth(paint, text, start, end)); | |
} | |
@Override | |
public void draw(@NonNull Canvas canvas, | |
CharSequence text, | |
int start, | |
int end, | |
float x, | |
int top, | |
int y, | |
int bottom, | |
@NonNull Paint paint | |
) { | |
paint.setColor(backgroundColor); | |
float size = measureWidth(paint, text, start, end); | |
canvas.drawCircle(x + size / 2, (bottom - top) / 2, size / 2, paint); | |
paint.setColor(textColor); | |
canvas.drawText(text, start, end, x + padding, y, paint); | |
} | |
private float measureWidth(Paint paint, CharSequence text, int start, int end) { | |
return paint.measureText(text, start, end) + 2 * padding; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment