Add text to image in android programmatically

前端 未结 4 1231
走了就别回头了
走了就别回头了 2020-12-14 21:21

I want to make an application just like opening screen of android.I am dynamically adding images to the rows of tableLayout. I have only defined tableLayout in xml file and

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 21:57

    Here's Kotlin version Arun's solution:

    import org.jetbrains.anko.dip
    
    fun Context.writeTextOnDrawable(drawableId: Int, text: String) =
            DrawableUtil.writeTextOnDrawableInternal(this, drawableId, text, 25, -2, 0)
    
    object DrawableUtil {
    
        fun writeTextOnDrawableInternal(context: Context, drawableId: Int, text: String,
                textSizeDp: Int, horizontalOffset: Int, verticalOffset: Int): BitmapDrawable {
    
            val bm = BitmapFactory.decodeResource(context.resources, drawableId)
                    .copy(Bitmap.Config.ARGB_8888, true)
    
            val tf = Typeface.create("Helvetica", Typeface.BOLD)
    
            val paint = Paint()
            paint.style = Paint.Style.FILL
            paint.color = Color.WHITE
            paint.typeface = tf
            paint.textAlign = Paint.Align.LEFT
            paint.textSize = context.dip(textSizeDp).toFloat()
    
            val textRect = Rect()
            paint.getTextBounds(text, 0, text.length, textRect)
    
            val canvas = Canvas(bm)
    
            //If the text is bigger than the canvas , reduce the font size
            if (textRect.width() >= canvas.getWidth() - 4)
                //the padding on either sides is considered as 4, so as to appropriately fit in the text
                paint.textSize = context.dip(12).toFloat()
    
            //Calculate the positions
            val xPos = canvas.width.toFloat()/2 + horizontalOffset  
    
            //"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
            val yPos = (canvas.height / 2 - (paint.descent() + paint.ascent()) / 2) + verticalOffset
    
            canvas.drawText(text, xPos, yPos, paint)
    
            return BitmapDrawable(context.resources, bm)
        }
    }
    

提交回复
热议问题