How to have an image with a dynamic text in it, all in a drawable, like the “today” action item on Google Calendar app?

前端 未结 2 1533
無奈伤痛
無奈伤痛 2021-02-19 07:43

Background

Google Calendar app has an action item that dynamically change according to the current day (\"today\"):

I\'m required to do a very similar

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-19 08:20

    OK, found the answer about how to have the same font for the TextPaint of the Drawable class I've made:

    mPaint.typeface = ResourcesCompat.getFont(context, R.font.lato)
    

    The result:

    Here's the full implementation of this class:

    class TextDrawable(context: Context, text: CharSequence) : Drawable() {
        companion object {
            private val DEFAULT_COLOR = Color.WHITE
            private val DEFAULT_TEXT_SIZE_IN_DP = 12
        }
    
        private val mTextBounds = Rect()
        private val mPaint: TextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
        private val mDrawable: Drawable?
    
        var text: CharSequence = text
            set (value) {
                field = value
                invalidateSelf()
            }
    
        init {
            mPaint.typeface = ResourcesCompat.getFont(context, R.font.lato)
            mPaint.color = DEFAULT_COLOR
            mPaint.textAlign = Align.CENTER
            val textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE_IN_DP.toFloat(), context.resources.displayMetrics)
            mPaint.textSize = textSize
            mDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_backtodate)
            mDrawable!!.setBounds(0, 0, mDrawable.intrinsicWidth, mDrawable.intrinsicHeight)
        }
    
        override fun draw(canvas: Canvas) {
            val bounds = bounds
            mDrawable!!.draw(canvas)
            mPaint.getTextBounds(text.toString(), 0, text.length, mTextBounds);
            val textHeight = mTextBounds.bottom - mTextBounds.top
            canvas.drawText(text as String?, (bounds.right / 2).toFloat(), (bounds.bottom.toFloat() + textHeight + 1) / 2, mPaint)
        }
    
        override fun getOpacity(): Int = mPaint.alpha
        override fun getIntrinsicWidth(): Int = mDrawable!!.intrinsicWidth
        override fun getIntrinsicHeight(): Int = mDrawable!!.intrinsicHeight
    
        override fun setAlpha(alpha: Int) {
            mPaint.alpha = alpha
            invalidateSelf()
        }
    
        override fun setColorFilter(filter: ColorFilter?) {
            mPaint.colorFilter = filter
            invalidateSelf()
        }
    
    }
    

    EDIT: this code is now complete and works well. It should work fine, and is partially based on Calendar app itself, as was recommended to me to look at (here and here) .

提交回复
热议问题