If you have any Android users using cocos2dx, this is not necessarily an easy task to solve, but it is doable when you go down the rabbit hole. This requires editing the Cocos2dxBitmap.java file, which means that any changes made can be overridden by the update. In principle, the methods used to measure text are, although incorrect, inadequate.
First, we need to add a new variable to TextProperty
private final int mX;
Then replace the computeTextProperty code as follows:
private static TextProperty computeTextProperty(final String pString, final int unusedWidth, final int unusedHeight, final Paint pPaint) { final FontMetricsInt fm = pPaint.getFontMetricsInt(); final int h = (int) Math.ceil(fm.bottom - fm.top); int maxContentWidth = 0; final String[] lines = Cocos2dxBitmap.splitString(pString, 0, 0, pPaint); /* Compute the max width. */ int temp = 0; float left = 0; for (final String line : lines) { //get a path from text Path path = new Path(); pPaint.getTextPath(line, 0, line.length(), 0, 0, path); RectF bounds = new RectF(); path.computeBounds(bounds, true); temp = (int) FloatMath.ceil(bounds.width()); //if the text extends to the left of 0 if (bounds.left < left) { left = bounds.left; } if (temp > maxContentWidth) { maxContentWidth = temp; //extend the width to account for text rendered to the left of 0 if (left < bounds.left) { maxContentWidth += (int) FloatMath.ceil(Math.abs(left)); } } } left = Math.abs(left); return new TextProperty(maxContentWidth, h, lines, (int) FloatMath.ceil(left)); }
What basically happened is that we used the information returned by text to get if the left border is less than 0, which means that it will be displayed outside the bitmap. We also expand the width when there are several lines of text, since we are going to shift everything to fit the left borders, we also need offset borders.
Finally, replace computeX with
private static int computeX(final String pText, final int pMaxWidth, final int pHorizontalAlignment, final int pX) { int ret = 0; int expectedWidth = pX + pMaxWidth; switch (pHorizontalAlignment) { case HORIZONTALALIGN_CENTER: ret = expectedWidth / 2; break; case HORIZONTALALIGN_RIGHT: ret = expectedWidth; break; case HORIZONTALALIGN_LEFT: ret = pX; default: break; } return ret; }
You will need to make all the connections yourself, but this will provide the most accurate rendering of the text.