Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class AvatarPlaceholder(
- private val name: String,
- textGenerator: TextGenerator,
- colorGenerator: ColorGenerator
- ) : Drawable() {
- interface ColorGenerator {
- fun getColor(name: String): Int
- }
- interface TextGenerator {
- fun getText(name: String): String
- }
- companion object {
- private const val RATIO_TEXT_SIZE = 1 / 1.5f
- }
- private val backgroundPaint = Paint().apply {
- isAntiAlias = true
- color = colorGenerator.getColor(name)
- }
- private lateinit var boundsCopy: Rect
- private lateinit var textPaint: Paint
- private var textY: Float? = null
- private var textX: Float? = null
- private val text = textGenerator.getText(name)
- override fun draw(canvas: Canvas) {
- if (!::boundsCopy.isInitialized) {
- boundsCopy = Rect()
- copyBounds(boundsCopy)
- textPaint = Paint().apply {
- isAntiAlias = true
- color = Color.WHITE
- typeface = Typeface.create("sans-serif-light", Typeface.NORMAL)
- textSize = boundsCopy.height() * RATIO_TEXT_SIZE
- }
- textX = textPaint.measureText(text).let {
- boundsCopy.exactCenterX() - (it / 2)
- }
- textY = textPaint.measureText(text).let {
- boundsCopy.exactCenterY() - ((textPaint.ascent() + textPaint.descent()) / 2)
- }
- }
- val path = Path().apply {
- fillType = Path.FillType.WINDING
- addRoundRect(
- 0f,
- 0f,
- boundsCopy.width().toFloat(),
- boundsCopy.height().toFloat(),
- boundsCopy.exactCenterX(),
- boundsCopy.exactCenterY(),
- Path.Direction.CW
- )
- }
- canvas.drawPath(path, backgroundPaint)
- canvas.drawText(text, textX!!, textY!!, textPaint)
- }
- override fun setAlpha(alpha: Int) {
- backgroundPaint.alpha = alpha
- textPaint.alpha = alpha
- }
- override fun getOpacity(): Int {
- return PixelFormat.TRANSLUCENT
- }
- override fun setColorFilter(colorFilter: ColorFilter) {
- backgroundPaint.colorFilter = colorFilter
- textPaint.colorFilter = colorFilter
- }
- }
Add Comment
Please, Sign In to add comment