ios - CoreText 和右对齐

标签 ios core-text

我正在编写一个生成 PDF 的类,我会在完成后发布!

我无法将文本右对齐,使用 CTParagraphStyle,文本总是在左边。这怎么可能?我哪里错了?

- (void)addText:(NSString *)text color:(UIColor *)color fontSize:(CGFloat)size floating:(BOOL)floating {
CGContextSaveGState(pdfContext);

// Prepare font
CTFontRef font = CTFontCreateWithName(CFSTR("Verdana"), size, NULL);

// Font color
CGColorRef fontColor = [color CGColor];

// Paragraph
CTTextAlignment alignment = kCTRightTextAlignment;

CTParagraphStyleSetting settings[] = {
    {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment}
};

CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, sizeof(settings) / sizeof(settings[0]));

// Create an attributed string
CFStringRef keys[] = { kCTFontAttributeName , kCTParagraphStyleAttributeName, kCTForegroundColorAttributeName};
CFTypeRef values[] = { font, paragraphStyle, fontColor};
CFDictionaryRef attr = CFDictionaryCreate(NULL, (const void **)&keys, (const void **)&values,
                                          sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFAttributedStringRef attrString = CFAttributedStringCreate(NULL, (CFStringRef)text, attr);

CFRelease(paragraphStyle);
CFRelease(attr);

// Draw the string
CTLineRef line = CTLineCreateWithAttributedString(attrString);

CGContextSetTextPosition(pdfContext, xPadding, [self relativeHeight:currentHeight+size]);


CTLineDraw(line, pdfContext);

// Clean up
CFRelease(line);
CFRelease(attrString);
CFRelease(font);

CGContextRestoreGState(pdfContext);

if(floating == NO) {
    currentHeight += size;
}

最佳答案

删除CTLineDraw()及其相关代码,使用CTFrameDraw()

试试这个:

// Create the Core Text framesetter using the attributed string.
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString);

// Create the Core Text frame using our current view rect bounds.
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.bounds];
CTFrameRef frame =  CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), [path CGPath], NULL);
CTFrameDraw(frame, pdfContext);

关于ios - CoreText 和右对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13091336/

相关文章:

iphone - 从(子) View 返回时更改 View 标题

ios - Xcode 7.3 中未显示导航栏

ios - 带有太长阿拉伯文本的 CoreText

ios - 如何使用 Core Text 获取最后一个字符的矩形

ios7 - CGGlyph 取决于字体大小吗?

iphone - iOS : Core Text - loosing context when drawing image inside a block

ios - 应用一段时间未使用后取消本地通知

ios - 为什么滚动 UITableView 比滚动 UIScrollView 响应更快?

c++ - 为 iOS 编译时通过 Makefile 加载 libxml 的正确方法

ios - CATextLayer 快速更改文本