【问题标题】:How can i convert UIFont to CGFontRef?I causes warning and not working如何将 UIFont 转换为 CGFontRef?我会导致警告并且无法正常工作
【发布时间】:2024-04-26 02:30:02
【问题描述】:

我已将 UIFont 声明为委托...并且在另一个文件中,我将该委托 UIColor 转换为 CGColorRef

CGColorRef *color = appdel.color.CGColor;

【问题讨论】:

    标签: iphone cocoa-touch core-graphics


    【解决方案1】:
    CGFontRef cgFont = CGFontCreateWithFontName((CFStringRef)uiFont.fontName);
    

    【讨论】:

    • 不考虑字体大小。您需要手动执行此操作。
    • 如果您使用 ARC,这也需要一个网桥。使用类似下面的东西对我有用:CGFontRef cgFont = CGFontCreateWithFontName((__bridge CFStringRef)uiFont.fontName);
    【解决方案2】:

    在 Swift 4 中,CGFontRef 已重命名为 CGFont。 转换很简单

    let font: CGFont? = CGFont(uiFont.fontName as CFString)

    【讨论】:

      【解决方案3】:

      您在主题中提出一个问题,而在正文中似乎是另一个问题。我会回复主题中的那个。

      您可以像这样简单地将 UIFont * 转换为 CGFontRef:

      UIFont *font = [UIFont fontWithName:@"Helvetica" size:10.0];
      CGFontRef cgFont = (CGFontRef) font;
      

      我还没有确认这是否是官方的做法,但它对我有用。

      更新:

      这有点奇怪,因为它有时会起作用,但有时却不起作用。例如,这有效:

      CGContextSetFont(context, (CGFontRef) font);
      

      但这不是:

      CTFontCreateWithGraphicsFont((CGFontRef) font, 10.0, nil, nil);
      

      【讨论】:

      • Apple 的 CATextLayer 文档明确表示您不能在请求 CGFontRef 的地方使用 UIFont 实例。这就引出了一个问题,CGFontRef/UIFont 是否是真正的免费桥接(我猜不是?)
      • CGContextSetFont(context, (CGFontRef) font) 对我也不起作用——即使我添加 __bridge 使其成为“桥接演员”,它也会默默地失败