Guest User

Untitled

a guest
Dec 13th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. class AvatarPlaceholder(
  2. private val name: String,
  3. textGenerator: TextGenerator,
  4. colorGenerator: ColorGenerator
  5. ) : Drawable() {
  6.  
  7. interface ColorGenerator {
  8. fun getColor(name: String): Int
  9. }
  10.  
  11. interface TextGenerator {
  12. fun getText(name: String): String
  13. }
  14.  
  15. companion object {
  16. private const val RATIO_TEXT_SIZE = 1 / 1.5f
  17. }
  18.  
  19. private val backgroundPaint = Paint().apply {
  20. isAntiAlias = true
  21. color = colorGenerator.getColor(name)
  22. }
  23.  
  24. private lateinit var boundsCopy: Rect
  25. private lateinit var textPaint: Paint
  26. private var textY: Float? = null
  27. private var textX: Float? = null
  28. private val text = textGenerator.getText(name)
  29.  
  30. override fun draw(canvas: Canvas) {
  31. if (!::boundsCopy.isInitialized) {
  32. boundsCopy = Rect()
  33. copyBounds(boundsCopy)
  34. textPaint = Paint().apply {
  35. isAntiAlias = true
  36. color = Color.WHITE
  37. typeface = Typeface.create("sans-serif-light", Typeface.NORMAL)
  38. textSize = boundsCopy.height() * RATIO_TEXT_SIZE
  39. }
  40. textX = textPaint.measureText(text).let {
  41. boundsCopy.exactCenterX() - (it / 2)
  42. }
  43. textY = textPaint.measureText(text).let {
  44. boundsCopy.exactCenterY() - ((textPaint.ascent() + textPaint.descent()) / 2)
  45. }
  46. }
  47. val path = Path().apply {
  48. fillType = Path.FillType.WINDING
  49. addRoundRect(
  50. 0f,
  51. 0f,
  52. boundsCopy.width().toFloat(),
  53. boundsCopy.height().toFloat(),
  54. boundsCopy.exactCenterX(),
  55. boundsCopy.exactCenterY(),
  56. Path.Direction.CW
  57. )
  58. }
  59. canvas.drawPath(path, backgroundPaint)
  60. canvas.drawText(text, textX!!, textY!!, textPaint)
  61. }
  62.  
  63. override fun setAlpha(alpha: Int) {
  64. backgroundPaint.alpha = alpha
  65. textPaint.alpha = alpha
  66. }
  67.  
  68. override fun getOpacity(): Int {
  69. return PixelFormat.TRANSLUCENT
  70. }
  71.  
  72. override fun setColorFilter(colorFilter: ColorFilter) {
  73. backgroundPaint.colorFilter = colorFilter
  74. textPaint.colorFilter = colorFilter
  75. }
  76. }
Add Comment
Please, Sign In to add comment