gpt4 book ai didi

objective-c - 如何获取在 CTFrame 上绘制的文本的实际高度

转载 作者:太空狗 更新时间:2023-10-30 03:59:02 24 4
gpt4 key购买 nike

我有一定数量的文本填充了一些 CTFrame(不止一个)。为了创建所有框架(每个页面一个),我填充了一个框架,使用 CTFrameGetVisibleStringRange 获取不适合框架的文本并重复此过程,直到处理完所有文本。

在除最后一个框架之外的所有框架上,文本占据相同的页面高度。在最后一帧,我想知道文本占据的实际高度,以了解我可以从哪里开始绘制更多文本。

有什么办法吗?

更新

根据评论的要求,这是我使用@omz 的建议的解决方案:

我在我的项目中使用 ARC:

CTFrameRef locCTFrame = (__bridge CTFrameRef)ctFrame;

//Save CTLines
lines = (NSArray *) ((__bridge id)CTFrameGetLines(locCTFrame));

//Get line origins
CGPoint lOrigins[MAXLINESPERPAGE];
CTFrameGetLineOrigins(locCTFrame, CFRangeMake(0, 0), lOrigins);
CGFloat colHeight = self.frame.size.height;

//Save the amount of the height used by text
percentFull = ((colHeight - lOrigins[[lines count] - 1].y) / colHeight);

最佳答案

+ (CGSize)measureFrame:(CTFrameRef)frame
{
// 1. measure width
CFArrayRef lines = CTFrameGetLines(frame);
CFIndex numLines = CFArrayGetCount(lines);
CGFloat maxWidth = 0;

for(CFIndex index = 0; index < numLines; index++)
{
CTLineRef line = (CTLineRef) CFArrayGetValueAtIndex(lines, index);
CGFloat ascent, descent, leading, width;

width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);

if(width > maxWidth)
maxWidth = width;
}

// 2. measure height
CGFloat ascent, descent, leading;

CTLineGetTypographicBounds((CTLineRef) CFArrayGetValueAtIndex(lines, 0), &ascent, &descent, &leading);
CGFloat firstLineHeight = ascent + descent + leading;

CTLineGetTypographicBounds((CTLineRef) CFArrayGetValueAtIndex(lines, numLines - 1), &ascent, &descent, &leading);
CGFloat lastLineHeight = ascent + descent + leading;

CGPoint firstLineOrigin;
CTFrameGetLineOrigins(frame, CFRangeMake(0, 1), &firstLineOrigin);

CGPoint lastLineOrigin;
CTFrameGetLineOrigins(frame, CFRangeMake(numLines - 1, 1), &lastLineOrigin);

CGFloat textHeight = ABS(firstLineOrigin.y - lastLineOrigin.y) + firstLineHeight + lastLineHeight;

return CGSizeMake(maxWidth, textHeight);
}

关于objective-c - 如何获取在 CTFrame 上绘制的文本的实际高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8377496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com