Kad*_*efi 2 xcode text pdf-generation text-alignment swift
我试图移植一个客观的C方法来在PDF上下文中绘制文本到Swift.我可以转换大部分代码,但以下几行给我一个问题.转换中的一些帮助将是受欢迎的.这里是Objective C代码:
-(void)drawText:(NSString *)textToDraw context:(CGContextRef)myPDFContext textcolor:(NSColor *)textcolor textfont:(NSFont*)textfont textbox:(CGRect)boxsize pagesize:(CGSize)pageSize {
// .........
// create paragraph style and assign text alignment to it
CTTextAlignment alignment = kCTJustifiedTextAlignment;
CTParagraphStyleSetting _settings[] = { {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment} };
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(_settings, sizeof(_settings) / sizeof(_settings[0]));
// set paragraph style attribute
CFAttributedStringSetAttribute(attrStr, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTParagraphStyleAttributeName, paragraphStyle);
// .........
}
// The following lines are my try in Swift, but this gives errors:
func DrawText(textToDraw:String, myPDFContext:CGContextRef, textcolor:NSColor, textfont:NSFont, boxsize:CGRect, pagesize:CGSize) {
var alignment = CTTextAlignment.TextAlignmentLeft
let alignmentSetting = CTParagraphStyleSetting(spec: CTParagraphStyleSpecifier.Alignment, valueSize: sizeof(alignment), value: &alignment)
let paragraphStyle = CTParagraphStyleCreate(alignmentSetting, 1)
//.......
Run Code Online (Sandbox Code Playgroud)
如果这个问题得到解决,我可以在Swift中发布完整的方法.
我认为这样做:
var alignment = CTTextAlignment.TextAlignmentLeft
let alignmentSetting = [CTParagraphStyleSetting(spec: .Alignment, valueSize: UInt(sizeofValue(alignment)), value: &alignment)]
let paragraphStyle = CTParagraphStyleCreate(alignmentSetting, 1)
CFAttributedStringSetAttribute(attrStr, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTParagraphStyleAttributeName, paragraphStyle)
Run Code Online (Sandbox Code Playgroud)
我做了以下修改:
sizeof(alignment),UInt(sizeofValue(alignment))因为sizeof在Swift中只需要一个类型(例如sizeof(Int)).这UInt()是一个构造函数,通过此调用将Int返回的内容sizeofValue转换为UInt所需的内容.alignmentSetting进入一个数组,以便它可以传递给UnsafePointer那种类型.这也更好地匹配原始版本.CTParagraphStyleSpecifier.Alignment只是.Alignment因为第一部分不需要,因为spec是类型CTParagraphStyleSpecifier.1在这种情况下,硬编码是正常的,因为您只传递一个值,但更通用的解决方案是:
let paragraphStyle = CTParagraphStyleCreate(alignmentSetting, UInt(alignmentSetting.count))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3207 次 |
| 最近记录: |