【发布时间】:2014-08-01 10:13:36
【问题描述】:
我正在 iOS 中处理 coretext。
我通过将-drawRect 方法替换为以下代码,实现了自定义UIView:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGRect frameRect=CGRectMake(50, 200, 80, 15);
// NSString *textToDraw=@"A-BCDEFGHIJKLM";
// NSString *textToDraw=@"abc";
// NSString *textToDraw=@"ABCDEFGHIJKLMNOPQRST";
NSString *textToDraw=@"A-BCDEFGHIJ";
// NSString *textToDraw=@"A-BCDEFGHI";
CFStringRef stringRef = (__bridge CFStringRef)textToDraw;
NSMutableAttributedString* attString = [[NSMutableAttributedString alloc]initWithString:textToDraw];
NSInteger _stringLength=[textToDraw length];
CTTextAlignment theAlignment = kCTLeftTextAlignment; // kCTRightTextAlignment; //kCTCenterTextAlignment;
CTParagraphStyleSetting theSettings[1] =
{
{ kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment),&theAlignment
}
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(theSettings, 1);
[attString addAttribute:(id)kCTParagraphStyleAttributeName value:(__bridge id)paragraphStyle range:NSMakeRange(0, _stringLength)];
CFAttributedStringRef attrString =(__bridge CFAttributedStringRef) attString;
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
// Get the frame that will do the rendering.
CFRange currentRange = CFRangeMake(0, 0);
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
CGPathRelease(framePath);
// Get the graphics context.
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// Put the text matrix into a known state. This ensures
// that no old scaling factors are left in place.
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
// Core Text draws from the bottom-left corner up, so flip
// the current transform prior to drawing.
CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2);
CGContextScaleCTM(currentContext, 1.0, -1.0);
// Draw the frame.
CTFrameDraw(frameRef, currentContext);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2);
CFRelease(frameRef);
CFRelease(stringRef);
CFRelease(framesetter);
}
在这里,当我将输入字符串设置为“ABCDEFGHIJKLMNOPQRST”时,它会将我所需的输出作为“ABCDEFGHIJ”,根据宽度“80”截断'。
但问题是当我将输入字符串作为“A-BCDEFGHIJ” 传递时,它给我的输出是“A-”。
至少应按宽度打印“A-BCDEFGHI”。但它只打印“A-”。 它没有正确截断。
我的代码中是否缺少某些内容?
以下是截图:
字符串“ABCDEFGHIJKLMNOPQRST”的输出:
字符串“A-BCDEFGHIJ”的输出:
请帮帮我。
提前致谢。
【问题讨论】:
-
截图,也许...?
-
谢谢@holex。我已经更新了我的问题。
-
正确连字符,但第二行被截断,因为它会在
(.., .., 80, 15)的框架之外。增加框架的高度 - 或动态计算 - (对于更大的上下文),第二行将正确显示在您的屏幕上。
标签: ios objective-c core-graphics core-text