以编程方式获取TextEdit中所选文本的字体名称

时间:2012-07-30 08:33:38

标签: objective-c macos cocoa delphi-xe2 macos-carbon

尝试两个月后,我找到了如何从TextEdit(或任何NSTextView)的任何文本范围获取AttributedString。我的代码是:

AXUIElementRef systemWideElement = AXUIElementCreateSystemWide();
AXUIElementRef focussedElement = NULL;
AXError error = AXUIElementCopyAttributeValue(systemWideElement,
    kAXFocusedUIElementAttribute, (CFTypeRef*)&focussedElement);
if (error != kAXErrorSuccess) {
    println("Could not get focussed element");
}
else {
    AXValueRef selectedRangeValue = NULL;
    AXError getSelectedRangeError =
        AXUIElementCopyAttributeValue(focussedElement,
        kAXSelectedTextRangeAttribute, (CFTypeRef*)&selectedRangeValue);
    if (getSelectedRangeError == kAXErrorSuccess) {
        CFRange selectedRange;
        AXValueGetValue(selectedRangeValue, kAXValueCFRangeType,
            &selectedRange);
        AXValueRef attributedString = NULL;
        AXError getAttrStrError =
            AXUIElementCopyParameterizedAttributeValue(focussedElement,
            kAXAttributedStringForRangeParameterizedAttribute, selectedRangeValue,
            (CFTypeRef*)&attributedString);
        CFRelease(selectedRangeValue);

        if (getAttrStrError == kAXErrorSuccess)
        {
            CFAttributedStringRef attrStr = (CFAttributedStringRef)attributedString;

            CFTypeRef value = CFAttributedStringGetAttribute(
                attrStr, 0, kAXFontTextAttribute, NULL);

            println("value: %X", value); // value is not NULL, but I can't obtain font name from it.

            CFRelease(attributedString);
        }
        else
        {
            println("Could not get attributed string for selected range");
        }
    }
    else {
        println("Could not get selected range");
    }
}
if (focussedElement != NULL)
    CFRelease(focussedElement);
CFRelease(systemWideElement);

我正确地获得了CFAttributedStringRef(我可以从中获取长度或纯文本),但我无法获得字体名称

注意:

代码下面返回的值不是NULL:

CFTypeRef value = CFAttributedStringGetAttribute(
                attrStr, 0, kAXFontTextAttribute, NULL);

该值不能假设为CTFontRef或CGFontRef,ATSFontRef,...(导致异常)。

此外,我尝试kCTFontAttributeName而不是kAXFontTextAttribute,但返回NULL。

非常感谢。

2 个答案:

答案 0 :(得分:1)

与密钥kAXFontTextAttribute相关联的值似乎是CFDictionaryRef。请参阅AXTextAttributedString documentation

答案 1 :(得分:0)

这可以通过以下方式完成:

定义

NSFont *newFont;

提供默认字体,然后在字体管理器打开时,选择您的选择,然后创建按钮操作及其插座

然后,

NSFont*    oldFont = [NSFont fontWithName:@"Times" size:14];
NSFont*    newFont;
newFont = [sender convertFont:oldFont];
NSLog(@">>>>>>>>>>>: %@", newFont.fontName);