如何防止Cocos2d中的自定义字体出现截止

时间:2013-06-17 13:24:32

标签: cocos2d-iphone cclabelttf

我使用的是名为KomikaTitle的自定义字体。在某些情况下,字体在第一个字符的左侧显示为截断。当我使用Arial等本机字体时,不会发生这种情况。

以下是我正在使用的代码:

scoreDisplayLabel = [CCLabelTTF labelWithString:@"0" dimensions:CGSizeMake(200,30) hAlignment:UITextAlignmentLeft fontName:@"KomikaTitle" fontSize:18];
scoreDisplayLabel.color = (ccc3(r,b,g));
[self addChild:scoreDisplayLabel z:2];
[scoreDisplayLabel setPosition:ccp(115,wins.height-73)];

如何防止这种情况发生?我附上了问题的截图。

我按照http://www.cocos2d-iphone.org/forums/topic/custom-font-being-cut-off/的建议尝试搞乱,但没有运气。

enter image description here

谢谢你们!

3 个答案:

答案 0 :(得分:3)

这可能不是一个真正的答案,但我在我制作的旧cocos2d项目中遇到了与该字体相同的问题。刚刚添加了一个额外的空格和一行。

答案 1 :(得分:2)

这可能相关也可能不相关,但根据this source,您必须包含字体的文件扩展名。你在哪里

fontName:@"KomikaTitle"

应该是

fontName:@"KomikaTitle.ttf"

例如。

答案 2 :(得分:0)

如果有任何使用cocos2dx的安卓用户,这不一定是一个容易解决的问题,但是一旦你走下兔洞就可以了。它确实需要编辑Cocos2dxBitmap.java文件,这意味着所做的任何更改都可以被更新覆盖。基本上,用于衡量文本的方法虽然不是不正确,但不充分。

首先,我们需要在 TextProperty

中添加一个新变量

private final int mX;

接下来,使用以下内容替换 computeTextProperty 代码:

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)); }

基本上发生的是我们使用了文本路径返回的信息来获取左边界是否小于0,这意味着它将被渲染到位图之外。当有多行文本时我们也会扩展宽度,因为我们要将所有内容都移动到与左边界匹配,我们也需要移动右边界。

最后,将 computeX 替换为

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; }

你必须自己做所有的连接,但这将提供最准确的文本渲染。

相关问题