问题
I'm writing a custom View for a timer, but I can't get a properly fixed-width font for the numbers in the middle. Here's the relevant code (from two different methods):
mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTypeface(Typeface.create(Typeface.MONOSPACE, Typeface.NORMAL));
// Get rectangle that is the size of the text
mTextPaint.getTextBounds(
getTimeText(),
0,
getTimeText().length(),
mTextBounds);
// X and Y coordinates of text
float mTextPosX = (width / 2) - (mTextBounds.width() / 2);
float mTextPosY = (height / 2) + (mTextBounds.height() / 2);
// Draw text
canvas.drawText(
getTimeText(),
mTextPosX,
mTextPosY,
mTextPaint);
This seems to work fine, but whenever one of the numbers changes to a 1, that 1 takes up less space and the whole chunk of text moves over a bit. This obviously should not be happening, since I'm using a monospace font. Can anyone shed some light on how I might fix this?
回答1:
I had the same problem. A way to fix it is by using an external font in which "1" behaves as expected. A website with many fonts to try is this one: http://www.fontcubes.com/ . A related discussion on how to use external fonts in Android is here: How to change fontFamily of TextView in Android .
来源:https://stackoverflow.com/questions/17042721/android-monospace-fonts-arent-fixed-width