美文网首页
UILabel和CoreText展示的Emoji不一样的原因

UILabel和CoreText展示的Emoji不一样的原因

作者: 山已几孑 | 来源:发表于2023-11-21 15:40 被阅读0次

最近遇到一个小bug,当展示emoji的时候,两个地方展示的不一样,UILabel/UIButton中展示的是☺️,CoreText画出来的是
实际运行中,该表情的unicode值为\u263a,正确的展示为:☺️
测试时发现:
\u263a\ufe0f 转化的才是☺️,可参考在线unicode转换
\u263a 转化的就是,没毛病;
但是,在UILabel中\u263a就可以显示为☺️,CoreText中不行。
那为什么UILabel 中和通用的解析方式不一样呢?

思路:

UILabel和CoreText展示的Emoji不一样的原因可能有以下几种:

  • 编码方式不同:UILabel默认可以展示Emoji表情,但对于表情的编码方式有要求,而CoreText支持的编码方式可能不同。在UILabel中,需要使用Unicode编码来显示Emoji表情,而在CoreText中可能使用的是其他编码方式。
  • 字体不同:UILabel和CoreText使用的字体不同,可能会导致Emoji的显示效果不同。UILabel默认使用的是Apple的字体,而CoreText则可以使用不同的字体。
  • 渲染方式不同:UILabel和CoreText的渲染方式也可能不同,这也会影响Emoji的显示效果。UILabel使用的是iOS的渲染引擎,而CoreText则使用的是自己的渲染引擎。

因此,如果需要让UILabel和CoreText展示相同的Emoji效果,可以尝试以下方法:

  • 确保使用相同的编码方式:将文本转换为相同的编码方式,例如Unicode编码,然后再分别在UILabel和CoreText中显示。
  • 指定相同的字体:在使用CoreText时,可以指定与UILabel相同的字体,以确保Emoji的显示效果一致。
  • 调整渲染设置:可以尝试调整UILabel和CoreText的渲染设置,以使其效果更加接近。

测试过程

经测试发现,

// font1 的类型打印:<UICTFont: 0x13ff10fe0> font-family: ".SFUI-Regular"; font-weight: normal; font-style: normal; font-size: 15.00pt
UIFont * font1 = [UIFont systemFontOfSize:15];

//控制台中提示:CoreText note: Client requested name ".SFUI-Regular", it will get TimesNewRomanPSMT rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[UIFont systemFontOfSize:].
// 实际出的font2: <UICTFont: 0x14142a580> font-family: "Times New Roman"; font-weight: normal; font-style: normal; font-size: 15.00pt
UIFont * font2 = [UIFont fontWithName: font1.fontName size: font1.pointSize];

//控制台中提示:CoreText note: Client requested name ".SFUI-Regular", it will get TimesNewRomanPSMT rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[UIFont systemFontOfSize:].
//实际出的ctFont:<UICTFont: 0x141730120> font-family: "Times New Roman"; font-weight: normal; font-style: normal; font-size: 15.00pt
CTFontRef ctFont = CTFontCreateFromUIFont(style.font);

结论

问题就出在这里,UILabel/UIButton 和CoreText 最终使用的字体库是不一致的,因此导致了,对unicode解析的表情的处理方式不通,这里统一使用UIFont就可以了~

相关文章

网友评论

      本文标题:UILabel和CoreText展示的Emoji不一样的原因

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