【发布时间】:2012-03-21 17:17:59
【问题描述】:
我使用 Apple 的 SimpleTextInput 示例中的以下代码来确定光标的框架。我正在使用CTFrameGetLineOrigins,我注意到它返回的 y 值不正确(无论在哪一行,它都显示 .336)。我的应用程序与SimpleTextInput 略有不同,因为我将文本垂直居中,因此文本框架不会直接从原点开始。但是,为什么它给我每一行的这个价值?这是一个错误吗?
for (int i = 0; i < [lines count]; i++)
{
CTLineRef line = (CTLineRef) [lines objectAtIndex:i];
CFRange range = CTLineGetStringRange(line);
NSInteger localIndex = index - range.location;
if (localIndex >= 0 && localIndex <= range.length)
{
CGPoint origin;
CGFloat ascent, descent;
CTLineGetTypographicBounds(line, &ascent, &descent, NULL);
CTFrameGetLineOrigins(self.textFrame, CFRangeMake(i, 0), &origin);
CGFloat xPos = origin.x + CTLineGetOffsetForStringIndex(line, index, NULL);
return CGRectMake(xPos, origin.y - descent, 3, ascent + descent);
}
}
- (void) drawRect:(CGRect)rect
{
CTFramesetterRef textFramesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)self.text);
CGMutablePathRef textFrameMutablePath = CGPathCreateMutable();
CGPathAddRect(textFrameMutablePath, NULL, self.bounds);
self.textFrame = CTFramesetterCreateFrame(textFramesetter, CFRangeMake(0, 0), textFrameMutablePath, NULL);
CGFloat textFrameHeight = [self calculateHeightForTextFrame];
CGRect textFrameRect = CGRectMake(0, (self.bounds.size.height / 2) - (textFrameHeight / 2), self.bounds.size.width, textFrameHeight);
CGPathRelease(textFrameMutablePath);
textFrameMutablePath = NULL;
CFRelease(self.textFrame);
self.textFrame = NULL;
textFrameMutablePath = CGPathCreateMutable();
CGPathAddRect(textFrameMutablePath, NULL, textFrameRect);
self.textFrame = CTFramesetterCreateFrame(textFramesetter, CFRangeMake(0, 0), textFrameMutablePath, NULL);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CTFrameDraw(self.textFrame, context);
CGPathRelease(textFrameMutablePath);
CFRelease(textFramesetter);
[self cursorPositionChanged];
}
【问题讨论】:
标签: iphone ios cocoa-touch core-graphics core-text