How to calculate string font width in pixels?

前端 未结 3 459
星月不相逢
星月不相逢 2021-01-04 09:41

I want to calculate string font width in pixels in android. I am having string array and I am appending all these array elements to form one string. so I ha

相关标签:
3条回答
  • 2021-01-04 09:53

    I don't know if this works, but it can.

    int textSize=20;
    Paint p=new Paint();
    p.setTextSize(textSize);
    String string="Hello im a string.";
    public int getStringWidt()
    {
        return string.length*textSize;
    }
    
    0 讨论(0)
  • 2021-01-04 10:09

    Thanks Jake for the working solution, yet I found this to work for me too:

    someText = "Lorem Ipsum";
    TextView myTextView = (TextView) findViewById(R.id.myTextView);
    float w = myTextView.getPaint().measureText(someText);
    

    Getting the Paint directly from the TextView that I'm going to work with makes me feel that the anwser will be more accurate.

    0 讨论(0)
  • 2021-01-04 10:11

    Looks like there is a measureText method available on Paint. I also found an example:

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setStrokeWidth(5);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setTextSize(64);
    mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.ITALIC));
    // ...
    float w = mPaint.measureText(text, 0, text.length());
    
    0 讨论(0)
提交回复
热议问题