Detect whether a font is bold/italic on iOS?

前端 未结 4 1334
眼角桃花
眼角桃花 2020-12-15 06:21

Given a UIFont or a CTFont, how can I tell whether the font is bold/italic?

4条回答
  •  误落风尘
    2020-12-15 06:21

    Looking at the font's name won't always work. Consider the font "Courier Oblique" (which is italic) or "HoeflerText-Black" (which is bold), Neither of those contain "bold" or "italic" in their names.

    Given a font as a CTFontRef, the proper way to determine whether it's bold or italic is to use the CTFontGetSymbolicTraits function:

    CTFontRef font = CTFontCreateWithName((CFStringRef)@"Courier Oblique", 10, NULL);
    CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(font);
    BOOL isItalic = ((traits & kCTFontItalicTrait) == kCTFontItalicTrait);
    BOOL isBold = ((traits & kCTFontBoldTrait) == kCTFontBoldTrait);
    NSLog(@"Italic: %i Bold: %i", isItalic, isBold);
    CFRelease(font);
    

提交回复
热议问题