美文网首页
自定义字体的两种显示方法

自定义字体的两种显示方法

作者: 伏特加 | 来源:发表于2016-05-25 10:45 被阅读296次
    + (UIFont *)yq_cloudFontWithFilePath:(NSString *)filePath size:(CGFloat)size
    {
        UIFont *systemFont = [UIFont systemFontOfSize:size];
        if (![[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
            return systemFont;
        }
        CFURLRef fontURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (__bridge CFStringRef)filePath, kCFURLPOSIXPathStyle, false);
        CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(fontURL);
        if(!dataProvider) return systemFont;
        CFRelease(fontURL);
        CGFontRef graphicsFont = CGFontCreateWithDataProvider(dataProvider);
        CGDataProviderRelease(dataProvider);
        if (!graphicsFont) return systemFont;
        CTFontRef smallFont = CTFontCreateWithGraphicsFont(graphicsFont, size, NULL, NULL);
        CGFontRelease(graphicsFont);
        UIFont *returnFont = (__bridge UIFont *)smallFont;
        CFRelease(smallFont);
            return returnFont;
    }
    

    另一种如下:

    + (UIFont *)yq_cloudFontWithFilePath:(NSString *)filePath size:(CGFloat)size
    {
        UIFont *sysFont = [UIFont systemFontOfSize:size];
        if (![[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
            return sysFont;
        }
        CFURLRef fontURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (__bridge CFStringRef)filePath, kCFURLPOSIXPathStyle, false);
        CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(fontURL);
        if(!dataProvider) return sysFont;
        CFRelease(fontURL);
        CGFontRef fontRef = CGFontCreateWithDataProvider(dataProvider);
        CGDataProviderRelease(dataProvider);
        if (!fontRef) return sysFont;
        CFErrorRef errorRef;
        CFStringRef fontName = CGFontCopyPostScriptName(fontRef);
        NSString *fontNameCopy = (__bridge NSString *)(fontName);
        if ([[UIFont familyNames] containsObject:fontNameCopy]) {
            UIFont *font = [self fontWithName:(__bridge NSString *)(fontName) size:size];
            if (fontName) CFRelease(fontName);
            CGFontRelease(fontRef);
            return font;
        } else {
            BOOL suc = CTFontManagerRegisterGraphicsFont(fontRef, &errorRef);
            if (!suc) {
                CGFontRelease(fontRef);
                return sysFont;
            } else {
                UIFont *font = [self fontWithName:(__bridge NSString *)(fontName) size:size];
                if (fontName) CFRelease(fontName);
                CGFontRelease(fontRef);
                           return font;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:自定义字体的两种显示方法

          本文链接:https://www.haomeiwen.com/subject/izqtdttx.html