0

在尝试了两个月之后,我发现了如何从 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。

非常感谢。

4

2 回答 2

1

与键关联的值kAXFontTextAttribute似乎是CFDictionaryRef. 请参阅AXTextAttributedString 文档

于 2012-07-30T13:46:49.770 回答
0

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

定义

NSFont *newFont;

提供默认字体,然后当字体管理器打开时,选择您的选择,然后创建一个按钮操作及其出口

接着,

NSFont*    oldFont = [NSFont fontWithName:@"Times" size:14];
NSFont*    newFont;
newFont = [sender convertFont:oldFont];
NSLog(@">>>>>>>>>>>: %@", newFont.fontName);
于 2016-06-27T12:39:45.793 回答