Search code examples
javaandroidkotlintextdrawing

Trying to draw text inside a rectangle but plops of above it at android


new picture Right now I am trying to draw a text (a number) inside an rectangle which I draw. I want to make 2048 to learn more about the use cases of android and kotlin. But when I want to create the tiles I have a big problem. Usualy the numbers are supposest to be inside the rectangle but at my case they are one rectangle above the original one. So At the last row of tiles I have no numbers and at the top there are numbers above the actual gamefield. If you don't realy understand my question just write a comment, I will try to make it better then.

Important: just changing the y cord of the text doesn't help, it will just get overdrawn by the next rectangle then.

This is my class with which I am drawing the single tiles:

fun drawTile() {
        var number = tile.number
        var cordX = tile.x
        var cordY = tile.y

        shapeDrawable = ShapeDrawable(RectShape())
        shapeDrawable.setBounds(cordX, cordY, tileWidth, tileHeight)

        shapeDrawable.getPaint().color = tile.tileColor
        shapeDrawable.draw(canvas)

        if(number != 0) {

            var paintText = Paint(Paint.ANTI_ALIAS_FLAG)
            paintText.color = Color.BLACK
            paintText.textSize = 50f

            val numberString = "$number"

            paintText.setShadowLayer(10f, 10f, 10f, Color.BLACK)

            canvas.drawText(numberString, cordX.toFloat()+tileWidth/2, cordY.toFloat()+10, paintText) 

        }

        shapeDrawable.draw(canvas)

Here is an pic how it looks ingame


Solution

  • actually just changing the y coord should does the trick, you just need to draw the shape

    fun drawTile() {
            var number = tile.number
            var cordX = tile.x
            var cordY = tile.y
    
            shapeDrawable = ShapeDrawable(RectShape())
            shapeDrawable.setBounds(cordX, cordY, tileWidth, tileHeight)
    
            shapeDrawable.getPaint().color = tile.tileColor
    
            shapeDrawable.draw(canvas)
            if(number != 0) {
    
                var paintText = Paint(Paint.ANTI_ALIAS_FLAG)
                paintText.color = Color.BLACK
                paintText.textSize = 50f
    
                val numberString = "$number"
    
                paintText.setShadowLayer(10f, 10f, 10f, Color.BLACK)
    
                canvas.drawText(numberString, cordX.toFloat() + tileWidth/2, cordY.toFloat() + tileHeight / 2, paintText) 
    
            }