1

I am trying to convert code that uses NSFont to code that uses CTFont (trying to make it cross-platform for macOS and iOS).

to According to the documentation, and this post, I shouldn't have to do anything to make it work because there is a toll-free bridge between CTFontRef and NSFont.

Later, I am getting the error

error: cannot initialize a parameter of type 'NSFont * _Nonnull' with an lvalue of type 'CTFontRef' (aka 'const __CTFont *')
        convertedFont = [fontManager convertFont:convertedFont toNotHaveTrait:NSBoldFontMask];
                                                  ^~~~~~~~~~~~~

OLD CODE: (keeping NSFontManager for now)

NSFontManager *fontManager = [NSFontManager sharedFontManager];
//            NSFont *font = static_cast<NSFont *>(inProperties[theKey]);
//            NSFontTraitMask fontTraits = [fontManager traitsOfFont:font];
//            NSFont *convertedFont = font;

NEW CODE:

CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes((CFDictionaryRef)inProperties);
CTFontRef font = CTFontCreateWithFontDescriptor(descriptor, 0, NULL);
CFRelease(descriptor);
CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(font);
CTFontRef convertedFont = font;
Community
  • 1
  • 1
user101
  • 175
  • 1
  • 10

1 Answers1

1

Toll-free bridge between NSFont and CTFont means the following:

Given an NSFont object, it can be directly casted as CTFont object.

NSFont *fontObj = [NSFont systemFontOfSize:12];
CTFontRef coreFont = (__bridge CTFontRef)(fontObj);

Given a CTFont object, it can be directly casted to a NSFont object.

CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes((CFDictionaryRef)inProperties);
CTFontRef font = CTFontCreateWithFontDescriptor(descriptor, 0, NULL);
CFRelease(descriptor);
NSFont *nsFont = (__bridge NSFont *)(font);

I believe the mistake you are doing in your code is not casting your NSFont object to a CTFont object.

Please let me know if it resolves the problem

KrishnaCA
  • 5,615
  • 1
  • 21
  • 31