Created
March 13, 2020 07:01
-
-
Save m4kvn/8e55b37603e4b95faf30335ba5280b67 to your computer and use it in GitHub Desktop.
SpannableStringBuilderでテキストをラベル化するときに使う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
class LabelTextSpan( | |
@ColorInt private val labelColorInt: Int, | |
@ColorInt private val textColorInt: Int, | |
private val textSize: Float | |
) : ReplacementSpan() { | |
override fun draw( | |
canvas: Canvas, | |
text: CharSequence?, | |
start: Int, | |
end: Int, | |
x: Float, | |
top: Int, | |
y: Int, | |
bottom: Int, | |
paint: Paint | |
) { | |
text ?: return | |
canvas.save() | |
paint.isAntiAlias = true | |
paint.color = labelColorInt | |
val backgroundWidth = getSize(paint, text, start, end, paint.fontMetricsInt).toFloat() | |
val backgroundHeight = paint.descent() - paint.ascent() | |
val backgroundRect = RectF(0f, 0f, backgroundWidth, backgroundHeight) | |
canvas.translate(x, y + paint.ascent()) | |
canvas.drawRoundRect(backgroundRect, backgroundHeight, backgroundHeight, paint) | |
val textRect = RectF(backgroundRect) | |
paint.textSize = textSize | |
paint.color = textColorInt | |
textRect.right = paint.measureText(text, start, end) | |
textRect.bottom = paint.descent() - paint.ascent() | |
textRect.left += (backgroundRect.width() - textRect.right) / 2 | |
textRect.top += (backgroundRect.height() - textRect.bottom) / 2 | |
canvas.drawText(text, start, end, textRect.left, textRect.top - paint.ascent(), paint) | |
canvas.restore() | |
} | |
override fun getSize( | |
paint: Paint, | |
text: CharSequence?, | |
start: Int, | |
end: Int, | |
fm: Paint.FontMetricsInt? | |
): Int { | |
Log.d("TextBackgroundSpan", "text=$text, start=$start, end=$end") | |
text ?: return 0 | |
if (fm != null) { | |
val pfm = paint.fontMetricsInt | |
fm.ascent = pfm.ascent | |
fm.descent = pfm.descent | |
fm.top = pfm.top | |
fm.bottom = pfm.bottom | |
} | |
val fa = FloatArray(end - start) | |
paint.getTextWidths(text, start, end, fa) | |
Log.d("TextBackgroundSpan", "text=$text, fa=${fa.toList()}") | |
return fa.sum().toInt() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment