【问题标题】:NSString sizeWithFont: returning inconsistent results? known bug?NSString sizeWithFont:返回不一致的结果?已知的错误?
【发布时间】:2010-05-31 17:56:10
【问题描述】:

我正在尝试创建一个简单的自定义 UIView,它包含一个使用单一字体绘制的字符串,但第一个字符稍大。

我认为这很容易实现,两个 UILabel:s 并排放置。

我使用 NSString sizeWithFont 来测量我的字符串以便能够正确布局。

但我注意到返回矩形中的字体基线根据我设置的字体大小变化 +/- 1 像素。 这是我的代码:

NSString* ctxt = [text substringToIndex:1];
NSString* ttxt = [text substringFromIndex:1];

CGSize sz = [ctxt sizeWithFont: cfont ];
clbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, sz.width, sz.height)];
clbl.text = ctxt;
clbl.font = cfont;
clbl.backgroundColor = [UIColor clearColor];
[contentView addSubview:clbl];

CGSize sz2 = [ttxt sizeWithFont: tfont];
tlbl = [[UILabel alloc] initWithFrame:CGRectMake(sz.width, (sz.height - sz2.height), sz2.width, sz2.height)];
tlbl.text = ttxt;
tlbl.font = tfont;
tlbl.backgroundColor = [UIColor clearColor];
[contentView addSubview:tlbl];

如果我使用 12.0 和 14.0 作为尺寸,它可以正常工作。 但是如果我改用 13.0 和 15.0,那么第一个字符就高了 1 个像素。

这是一个已知问题吗?

有什么建议可以解决吗?

用 CSS 和 HTML 页面创建 UIWebView 似乎有点过头了。以及处理动态字符串的更多工作。这是我应该做的吗?

【问题讨论】:

  • 我也尝试将其实现为 drawRect:使用 [NSString drawInRect:] 确保问题不在 UILabel 中。同样的问题。

标签: iphone layout uiview nsstring sizewithfont


【解决方案1】:

找到答案了……

当然,我还要检查字体的下降值,并在布局中进行补偿。

第二个标签的新矩形是: CGRectMake(sz.width, (sz.height - sz2.height) + floor(cfont.descender - tfont.descender), sz2.width, sz2.height)

floor() 是为了确保它捕捉到像素位置,否则字体会看起来模糊

【讨论】:

  • 如果您找到了答案,请分享。
  • 我以为我做到了。为了更清楚,我将第二个标签的矩形更改为:CGRectMake(sz.width, (sz.height - sz2.height) + floor(cfont.descender - tfont.descender), sz2.width, sz2.height)
猜你喜欢
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多