Skip to content

Instantly share code, notes, and snippets.

@neworld
Created March 29, 2018 11:18
Show Gist options
  • Save neworld/4df561ca5d2242f4661008a8301f6c28 to your computer and use it in GitHub Desktop.
Save neworld/4df561ca5d2242f4661008a8301f6c28 to your computer and use it in GitHub Desktop.
package com.vinted.drawables
import android.content.res.ColorStateList
import android.graphics.*
import android.graphics.drawable.Drawable
import android.text.DynamicLayout
import android.text.Editable
import android.text.Layout
import android.text.TextPaint
/**
* @author Andrius Semionovas
* @since 2015-07-15
*/
class TextDrawable : Drawable() {
private val paint = TextPaint(Paint.ANTI_ALIAS_FLAG)
private val editable = Editable.Factory().newEditable("")
private val layout = DynamicLayout(editable, paint, Integer.MAX_VALUE, Layout.Alignment.ALIGN_NORMAL, 1f, 0f, false)
private val textBounds = Rect()
override fun draw(canvas: Canvas) {
layout.draw(canvas)
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
invalidateSelf()
}
override fun setColorFilter(cf: ColorFilter?) {
paint.colorFilter = cf
invalidateSelf()
}
override fun setTintList(tint: ColorStateList) {
setTint(tint.defaultColor)
}
override fun setTint(tintColor: Int) {
setTextColor(tintColor)
invalidateSelf()
}
fun setTextSize(size: Float) {
paint.textSize = size
invalidateSelf()
}
fun setText(text: CharSequence) {
editable.clear()
editable.append(text)
paint.getTextBounds(text.toString(), 0, text.length, textBounds)
invalidateSelf()
}
fun setTextColor(color: Int) {
paint.color = color
}
override fun getIntrinsicWidth() = DynamicLayout.getDesiredWidth(editable, paint).toInt()
override fun getIntrinsicHeight() = -textBounds.top + textBounds.bottom
override fun getOpacity() = PixelFormat.TRANSLUCENT
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment