ios 我可以在 iPhone 应用程序中嵌入自定义字体吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/360751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:26:49  来源:igfitidea点击:

Can I embed a custom font in an iPhone application?

ioscocoa-touchfonts

提问by Airsource Ltd

I would like to have an app include a custom font for rendering text, load it, and then use it with standard UIKitelements like UILabel. Is this possible?

我想让一个应用程序包含一个用于呈现文本的自定义字体,加载它,然后将它与标准UIKit元素一起使用,例如UILabel. 这可能吗?

采纳答案by samvermette

iOS 3.2 and later support this. Straight from the What's New in iPhone OS 3.2doc:

iOS 3.2 及更高版本支持此功能。直接来自iPhone OS 3.2 中的新增功能文档:

Custom Font Support
Applications that want to use custom fonts can now include those fonts in their application bundle and register those fonts with the system by including the UIAppFonts key in their Info.plist file. The value of this key is an array of strings identifying the font files in the application's bundle. When the system sees the key, it loads the specified fonts and makes them available to the application.

自定义字体支持
想要使用自定义字体的应用程序现在可以将这些字体包含在其应用程序包中,并通过在其 Info.plist 文件中包含 UIAppFonts 键来向系统注册这些字体。该键的值是一个字符串数组,用于标识应用程序包中的字体文件。当系统看到密钥时,它会加载指定的字体并使它们可供应用程序使用。

Once the fonts have been set in the Info.plist, you can use your custom fonts as any other font in IB or programatically.

在 中设置字体后Info.plist,您可以在 IB 中或以编程方式将自定义字体用作任何其他字体。

There is an ongoing thread on Apple Developer Forums:
https://devforums.apple.com/thread/37824(login required)

Apple 开发者论坛上有一个正在进行的主题:
https: //devforums.apple.com/thread/37824(需要登录)

And here's an excellent and simple 3 steps tutorial on how to achieve this (broken link removed)

这是一个关于如何实现这一目标的优秀而简单的 3 步教程(已删除断开的链接)

  1. Add your custom font files into your project using Xcode as a resource
  2. Add a key to your Info.plistfile called UIAppFonts.
  3. Make this key an array
  4. For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFontsarray
  5. Save Info.plist
  6. Now in your application you can simply call [UIFont fontWithName:@"CustomFontName" size:12]to get the custom font to use with your UILabelsand UITextViews, etc…
  1. 使用 Xcode 作为资源将您的自定义字体文件添加到您的项目中
  2. 向您的Info.plist文件中添加一个名为UIAppFonts.
  3. 将此键设为数组
  4. 对于您拥有的每种字体,输入字体文件的全名(包括扩展名)作为UIAppFonts数组的项
  5. 节省 Info.plist
  6. 现在,在您的应用程序中,您可以简单地调用[UIFont fontWithName:@"CustomFontName" size:12]以获取与UILabelsUITextViews等一起使用的自定义字体……

Also: Make sure the fonts are in your Copy Bundle Resources.

另外:确保字体在您的复制包资源中。

回答by commanda

Edit: As of iOS 3.2, this functionality is built in. If you need to support pre-3.2, you can still use this solution.

编辑:从 iOS 3.2 开始,这个功能是内置的。如果你需要支持 pre-3.2,你仍然可以使用这个解决方案。

I created a simple module that extends UILabeland handles loading .ttf files. I released it opensource under the Apache license and put it on github Here.

我创建了一个简单的模块来扩展UILabel和处理 .ttf 文件的加载。我在 Apache 许可下将其开源发布,并将其放在 github 上

The important files are FontLabel.hand FontLabel.m.

重要的文件是FontLabel.hFontLabel.m

It uses some of the code from Genericrich's answer.

它使用了Genericrich's answer 中的一些代码。

Browse the source Here.

此处浏览源代码

OR

或者

  • Copy your font file into resources

  • Add a key to your Info.plistfile called UIAppFonts. ("Fonts provided by application)

  • Make this key an array

  • For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array

  • Save Info.plist

  • Now in your application you can simply call [UIFont fontWithName:@"CustomFontName" size:15]to get the custom font to use with your UILabelsand UITextViews, etc…

  • 将您的字体文件复制到资源中

  • 向您的Info.plist文件中添加一个名为 UIAppFonts 的密钥。(“应用程序提供的字体)

  • 将此键设为数组

  • 对于您拥有的每种字体,输入字体文件的全名(包括扩展名)作为 UIAppFonts 数组的项

  • 节省 Info.plist

  • 现在,在您的应用程序中,您可以简单地调用[UIFont fontWithName:@"CustomFontName" size:15]以获取与您的UILabelsUITextViews等一起使用的自定义字体……

For More Information

想要查询更多的信息

回答by alexey

There is a simple way to use custom fonts in iOS 4.

iOS 4 中有一种使用自定义字体的简单方法。

  1. Add your font file (for example, Chalkduster.ttf) to Resourcesfolder of the project in XCode.
  2. Open info.plistand add a new key called UIAppFonts. The type of this key should be array.
  3. Add your custom font name to this array including extension (Chalkduster.ttf).
  4. Now you can use [UIFont fontWithName:@"Chalkduster" size:16]in your application.
  1. 将您的字体文件(例如,Chalkduster.ttf)添加到XCode 项目的Resources文件夹中。
  2. 打开info.plist并添加一个名为 的新密钥UIAppFonts。这个键的类型应该是数组。
  3. 将您的自定义字体名称添加到此数组,包括扩展名 ( Chalkduster.ttf)。
  4. 现在您可以[UIFont fontWithName:@"Chalkduster" size:16]在您的应用程序中使用。

Unfortunately, IB doesn't allow to initialize labels with custom fonts. See this questionto solve this problem. My favorite solution is to use custom UILabelsubclass:

不幸的是,IB 不允许使用自定义字体初始化标签。看到这个问题来解决这个问题。我最喜欢的解决方案是使用自定义UILabel子类:

@implementation CustomFontLabel

- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super initWithCoder: decoder])
    {
        [self setFont: [UIFont fontWithName: @"Chalkduster" size: self.font.pointSize]];
    }
    return self;
}

@end

回答by bdev

In Info.plist add the entry "Fonts provided by application" and include the font names as strings:

在 Info.plist 中添加条目“应用程序提供的字体”并将字体名称包含为字符串:

Fonts provided by application
           Item 0        myfontname.ttf
           Item 1        myfontname-bold.ttf
           ...

Then check to make sure your font is included by running :

然后通过运行检查以确保您的字体包含在内:

for (NSString *familyName in [UIFont familyNames]) {
    for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
         NSLog(@"%@", fontName);
    }
}

Note that your ttf file name might not be the same name that you use when you set the font for your label (you can use the code above to get the "fontWithName" parameter):

请注意,您的 ttf 文件名可能与您为标签设置字体时使用的名称不同(您可以使用上面的代码获取“fontWithName”参数):

[label setFont:[UIFont fontWithName:@"MyFontName-Regular" size:18]];

回答by rpetrich

edit: This answer is defunct as of iOS3.2; use UIAppFonts

编辑:此答案自 iOS3.2 起已失效;使用 UIAppFonts

The only way I've been able to successfully load custom UIFonts is via the private GraphicsServices framework.

我能够成功加载自定义UIFonts的唯一方法是通过私有 GraphicsServices 框架。

The following will load all the .ttffonts in the application's main bundle:

以下将加载.ttf应用程序主包中的所有字体:

BOOL GSFontAddFromFile(const char * path);
NSUInteger loadFonts()
{
    NSUInteger newFontCount = 0;
    for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:@"ttf" inDirectory:nil])
        newFontCount += GSFontAddFromFile([fontFile UTF8String]);
    return newFontCount;
}

Once fonts are loaded, they can be used just like the Apple-provided fonts:

加载字体后,它们可以像 Apple 提供的字体一样使用:

NSLog(@"Available Font Families: %@", [UIFont familyNames]);
[label setFont:[UIFont fontWithName:@"Consolas" size:20.0f]];

GraphicsServices can even be loaded at runtime in case the API disappears in the future:

GraphicsServices 甚至可以在运行时加载,以防将来 API 消失:

#import <dlfcn.h>
NSUInteger loadFonts()
{
    NSUInteger newFontCount = 0;
    NSBundle *frameworkBundle = [NSBundle bundleWithIdentifier:@"com.apple.GraphicsServices"];
    const char *frameworkPath = [[frameworkBundle executablePath] UTF8String];
    if (frameworkPath) {
        void *graphicsServices = dlopen(frameworkPath, RTLD_NOLOAD | RTLD_LAZY);
        if (graphicsServices) {
            BOOL (*GSFontAddFromFile)(const char *) = dlsym(graphicsServices, "GSFontAddFromFile");
            if (GSFontAddFromFile)
                for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:@"ttf" inDirectory:nil])
                    newFontCount += GSFontAddFromFile([fontFile UTF8String]);
        }
    }
    return newFontCount;
}

回答by Dima Deplov

With iOS 8+ and Xcode 6+ you can make this easily. Here are the steps:

使用iOS 8+ 和Xcode 6+ 您可以轻松做到这一点。以下是步骤:

1) Drag and drop your font to XcodeSupporting Files folder. Don't forget to mark your app at Add to targetssection. From this moment you can use this font in IBand choose it from font pallet.

1) 将您的字体拖放到XcodeSupporting Files 文件夹中。不要忘记在添加到目标部分标记您的应用程序。从这一刻起,您可以使用此字体IB并从字体托盘中选择它。

enter image description here

在此处输入图片说明

2) To make this font available to in your device, open your info.plistand add Fonts provided by applicationkey. It will contain Item 0 key, you must add your font name as the value. Font name can vary from your font file name. But first, try to add your filename in most cases this work.

2) 要在您的设备中使用此字体,请打开您的info.plist并添加Fonts provided by application密钥。它将包含 Item 0 键,您必须添加您的字体名称作为值。字体名称可能与您的字体文件名不同。但首先,在大多数情况下尝试添加您的文件名。

enter image description here

在此处输入图片说明

If not, this articlealways helped me.

如果没有,这篇文章总是对我有帮助。

Here is swift snippet of the code from this article to help you find your font name.

这是本文中代码的快速片段,可帮助您找到字体名称。

func allFonts(){

   for family in UIFont.familyNames(){

       println(family)


       for name in UIFont.fontNamesForFamilyName(family.description)
       {
           println("  \(name)")
       }

   }

}

EDIT

编辑

I want to mention, that you need to add font files to your Target's Build Phases, Copy Bundle Resources. Without it, you won't see your font on the device. And it could lead to unexpected behaviour.

我想提一下,您需要将字体文件添加到Target 的 Build PhasesCopy Bundle Resources。没有它,您将无法在设备上看到您的字体。它可能会导致意外行为。

For example, I encounter a bug, when UITextFieldhave custom font, but this font wasn't in the Copy Bundle Resources. And when I segue to the viewcontrollerwith this textfield, there is a delay about 4 seconds before viewDidLoadfunction was called. Resolving font troubles removed this delay. So, recommend to check it twice. (rdar://20028250) Btw, I wasn't able to reproduce the bug, but I'm sure that problem was with the font.

例如,bugUITextField有自定义字体时,我遇到了,但这种字体不在Copy Bundle Resources 中。当我继续viewcontroller使用 this 时textfield,在viewDidLoad调用函数之前有大约 4 秒的延迟。解决字体问题消除了这种延迟。所以,建议检查两次。(rdar://20028250) 顺便说一句,我无法重现该错误,但我确定问题出在字体上。

回答by Genericrich

I have done this like this:

我这样做了:

Load the font:

加载字体:

- (void)loadFont{
  // Get the path to our custom font and create a data provider.
  NSString *fontPath = [[NSBundle mainBundle] pathForResource:@"mycustomfont" ofType:@"ttf"]; 
  CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);

  // Create the font with the data provider, then release the data provider.
  customFont = CGFontCreateWithDataProvider(fontDataProvider);
  CGDataProviderRelease(fontDataProvider); 
}

Now, in your drawRect:, do something like this:

现在,在你的drawRect:,做这样的事情:

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    // Get the context.
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    // Set the customFont to be the font used to draw.
    CGContextSetFont(context, customFont);

    // Set how the context draws the font, what color, how big.
    CGContextSetTextDrawingMode(context, kCGTextFillStroke);
    CGContextSetFillColorWithColor(context, self.fontColor.CGColor);
    UIColor * strokeColor = [UIColor blackColor];
    CGContextSetStrokeColorWithColor(context, strokeColor.CGColor);
    CGContextSetFontSize(context, 48.0f);

    // Create an array of Glyph's the size of text that will be drawn.
    CGGlyph textToPrint[[self.theText length]];

    // Loop through the entire length of the text.
    for (int i = 0; i < [self.theText length]; ++i) {
        // Store each letter in a Glyph and subtract the MagicNumber to get appropriate value.
        textToPrint[i] = [[self.theText uppercaseString] characterAtIndex:i] + 3 - 32;
    }
    CGAffineTransform textTransform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
    CGContextSetTextMatrix(context, textTransform);
    CGContextShowGlyphsAtPoint(context, 20, 50, textToPrint, [self.theText length]);
}

Basically you have to do some brute force looping through the text and futzing about with the magic number to find your offset (here, see me using 29) in the font, but it works.

基本上,您必须在文本中执行一些蛮力循环并使用幻数来查找字体中的偏移量(在这里,请参阅我使用 29),但它有效。

Also, you have to make sure the font is legally embeddable. Most aren't and there are lawyers who specialize in this sort of thing, so be warned.

此外,您必须确保字体可合法嵌入。大多数不是,并且有专门从事此类事情的律师,因此请注意。

回答by August

Yes, you can include custom fonts. Refer to the documentation on UIFont, specifically, the fontWithName:size:method.

是的,您可以包含自定义字体。请参阅有关 UIFont 的文档,特别是fontWithName:size:方法。

1) Make sure you include the font in your resources folder.

1) 确保在资源文件夹中包含字体。

2) The "name" of the font is not necessarily the filename.

2) 字体的“名称”不一定是文件名。

3) Make sure you have the legal right to use that font. By including it in your app, you're also distributing it, and you need to have the right to do that.

3) 确保您拥有使用该字体的合法权利。通过将它包含在您的应用程序中,您也在分发它,您需要有权这样做。

回答by SKris

If you are using xcode 4.3, you have to add the fontto the Build Phaseunder Copy Bundle Resources, according to https://stackoverflow.com/users/1292829/arnein the thread, Custom Fonts Xcode 4.3. This worked for me, here are the steps I took for custom fonts to work in my app:

如果你正在使用xcode 4.3,您必须添加fontBuild PhaseCopy Bundle Resources,根据https://stackoverflow.com/users/1292829/arne在线程,自定义字体的Xcode 4.3。这对我有用,以下是我为在我的应用程序中使用自定义字体而采取的步骤:

  1. Add the font to your project. I dragged and dropped the OTF(or TTF) files to a new group I created and accepted xcode's choice of copying the files over to the project folder.
  2. Create the UIAppFontsarray with your fonts listed as items within the array. Just the names, not the extension (e.g. "GothamBold", "GothamBold-Italic").
  3. Click on the project nameway at the top of the Project Navigatoron the left side of the screen.
  4. Click on the Build Phasestab that appears in the main area of xcode.
  5. Expand the "Copy Bundle Resources" section and click on "+"to add the font.
  6. Select the font file from the file navigator that pops open when you click on the "+".
  7. Do this for every font you have to add to the project.
  1. 将字体添加到您的项目中。我将OTF(或TTF)文件拖放到我创建的新组中,并接受了 xcode 的copying the files over to the project folder.
  2. 创建UIAppFonts数组,将您的字体列为数组中的项目。只是names,而不是扩展名(例如“ GothamBold”、“ GothamBold-Italic”)。
  3. 单击屏幕左侧project name顶部的路径Project Navigator
  4. 单击Build Phases出现在 xcode 主要区域中的选项卡。
  5. 展开“ Copy Bundle Resources”部分并单击"+"以添加字体。
  6. 从文件导航器中选择字体文件,当您单击"+".
  7. 对您必须使用的每种字体执行此操作add to the project

回答by kumar123

It is very easy to add a new font on your existing iOS App.

在现有的 iOS 应用程序上添加新字体非常容易。

You just need to add the font e.g. font.ttf into your Resource Folder.

您只需要将字体(例如 font.ttf)添加到您的资源文件夹中。

Open your application info.plist. Add a new row as "Fonts provided by application" and type the font name as font.ttf.

打开您的应用程序info.plist。添加一个新行作为“应用程序提供的字体”并键入字体名称作为 font.ttf。

And when setting the font do as setFont:"corresponding Font Name"

当设置字体时 setFont:"corresponding Font Name"

You can check whether your font is added or not by NSArray *check = [UIFont familyNames];.

您可以通过NSArray *check = [UIFont familyNames];.

It returns all the font your application support.

它返回您的应用程序支持的所有字体。