UILabel 获取文本子字符串的 CGRect

发布于 11-26 04:27 字数 353 浏览 1 评论 0原文

我的目标很简单:从 UILabel 获取标签文本中子字符串的矩形。从广泛的搜索来看,似乎没有任何内置的东西可以处理这个问题。其他人也提出过类似的问题,但在 Stackoverflow 上都没有得到完整的回答。

// Something like this perhaps (added as a category)
CGRect rect = [myLabel rectForRange:NSMakeRange(3, 5)];

它的用途示例(只是为了澄清我正在搜索的内容):

example of rect

My objective is simple: From a UILabel get the rect of a substring in the text of the label. From extensive searching there doesn't appear to be anything built in to handle this. Other people have asked similar questions, but none have been answered fully here on Stackoverflow.

// Something like this perhaps (added as a category)
CGRect rect = [myLabel rectForRange:NSMakeRange(3, 5)];

An example of what it could be used for (just to clarify what I'm searching for):

example of rect

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

痴情换悲伤2024-12-03 04:27:47

这主要是一个字符矩形所需要的,所以我疯狂地编写了一些代码,可以准确计算最基本的 UILabel 的矩形。标准 UILineBreakMode 和文本对齐方式。

我希望如果我将它发布给公众,人们的代码会对其做出贡献并改进它,特别是因为我对文本渲染不太了解!

代码:

https://gist.github.com/1278483

This was mostly needed for one character rects, so I went crazy and wrote some code that could accurately calculate the rect for the most basic UILabel. Standard UILineBreakMode and text alignment.

I was hoping that if I release it to the public people code contribute to it and improve it, especially since I don't know so much about text rendering!

The code:

https://gist.github.com/1278483

雨的味道风的声音2024-12-03 04:27:47

你是对的:这不是 UILabel 的内置部分。

如果你确实需要这个,子类 UILabel,使用 CoreText 实现 -drawRect:,你将能够 通过CTLineGetOffsetForStringIndex()计算范围的矩形CTFrameGetLineOrigins()CTLineGetTypgraphicBounds()。如果范围内的文本被布置为跨越换行符,这将变得复杂;你可能需要多个矩形。

You're right: this isn't a built-in part of UILabel.

If you really need this, subclass UILabel, use CoreText to implement -drawRect:, and you'll be able to compute the rect for a range via CTLineGetOffsetForStringIndex(), CTFrameGetLineOrigins(), and CTLineGetTypographicBounds(). If the text in the range gets laid out so as to cross a line break, this will get complicated; you'll likely want multiple rects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文