Skip to content

Instantly share code, notes, and snippets.

@m4kvn
Created March 13, 2020 07:01
Show Gist options
  • Save m4kvn/8e55b37603e4b95faf30335ba5280b67 to your computer and use it in GitHub Desktop.
Save m4kvn/8e55b37603e4b95faf30335ba5280b67 to your computer and use it in GitHub Desktop.
SpannableStringBuilderでテキストをラベル化するときに使うSpan
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