Measuring text width to be drawn on Canvas ( Android )

前端 未结 7 1835
轮回少年
轮回少年 2020-12-12 16:18

Is there a method which returns the width ( in pixels ) of a text to be drawn on an Android canvas using the drawText() method according to the Paint used to draw it?

7条回答
  •  再見小時候
    2020-12-12 16:32

    Well I have done in different way:

    String finalVal ="Hiren Patel";
    
    Paint paint = new Paint();
    paint.setTextSize(40);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "Helvetica.ttf");
    paint.setTypeface(typeface);
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.FILL);
    
    Rect result = new Rect();
    paint.getTextBounds(finalVal, 0, finalVal.length(), result);
    
    Log.i("Text dimensions", "Width: "+result.width()+"-Height: "+result.height());
    

    Hope this will help you.

提交回复
热议问题