Draw text inside a filled rectangle using Canvas Android

前端 未结 3 1987
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 02:26

How to draw a filled rectangle with specified bounds and inside that rectangle text to be drawn using Canvas Android ?? I tried

mPaint.setColor(Color.GREEN)         


        
3条回答
  •  伪装坚强ぢ
    2021-01-03 02:42

    If you have to center the text inside de rect you have use this code

        mpaint= new Paint();
        mpaint.setColor(Color.RED);
        mpaint.setStyle(Style.FILL);
        paint2= new Paint();
        paint2.setColor(Color.GREEN);
        paint2.setTextSize(50);  //set text size
        float w = paint2.measureText(s)/2;
        float textSize = paint2.getTextSize();
    
    
        @Override
        protected void onDraw(Canvas canvas) {
            paint2.setTextAlign(Paint.Align.CENTER);
            Rect rect = new Rect(300-w, 300 - textsize, 300 + w, 300);
            canvas.drawRect(rect, mpaint);
            canvas.drawText(s, rect.centerX(), rect.centerY() ,paint2); // center text inside rect
        }
    

提交回复
热议问题