|
42 | 42 | @RestrictTo(LIBRARY_GROUP) |
43 | 43 | @RequiresApi(29) |
44 | 44 | public class TypefaceCompatApi29Impl extends TypefaceCompatBaseImpl { |
| 45 | + |
| 46 | + private static int getMatchScore(@NonNull FontStyle o1, @NonNull FontStyle o2) { |
| 47 | + return Math.abs((o1.getWeight() - o2.getWeight())) / 100 + (o1.getSlant() == o2.getSlant() ? 0 : 2); |
| 48 | + } |
| 49 | + |
| 50 | + private Font findBaseFont(@NonNull FontFamily family) { |
| 51 | + final FontStyle normal = new FontStyle(FontStyle.FONT_WEIGHT_NORMAL, |
| 52 | + FontStyle.FONT_SLANT_UPRIGHT); |
| 53 | + Font bestFont = family.getFont(0); |
| 54 | + int bestScore = getMatchScore(normal, bestFont.getStyle()); |
| 55 | + for (int i = 1; i < family.getSize(); ++i) { |
| 56 | + final Font candidate = family.getFont(i); |
| 57 | + final int score = getMatchScore(normal, candidate.getStyle()); |
| 58 | + if (score < bestScore) { |
| 59 | + bestFont = candidate; |
| 60 | + bestScore = score; |
| 61 | + } |
| 62 | + } |
| 63 | + return bestFont; |
| 64 | + } |
| 65 | + |
45 | 66 | @Override |
46 | 67 | protected FontsContractCompat.FontInfo findBestInfo(FontsContractCompat.FontInfo[] fonts, |
47 | 68 | int style) { |
@@ -86,14 +107,9 @@ public Typeface createFromFontInfo(Context context, |
86 | 107 | if (familyBuilder == null) { |
87 | 108 | return null; // No font is added. Give up. |
88 | 109 | } |
89 | | - final FontStyle defaultStyle = new FontStyle( |
90 | | - (style & Typeface.BOLD) != 0 ? FontStyle.FONT_WEIGHT_BOLD |
91 | | - : FontStyle.FONT_WEIGHT_NORMAL, |
92 | | - (style & Typeface.ITALIC) != 0 ? FontStyle.FONT_SLANT_ITALIC |
93 | | - : FontStyle.FONT_SLANT_UPRIGHT |
94 | | - ); |
95 | | - return new Typeface.CustomFallbackBuilder(familyBuilder.build()) |
96 | | - .setStyle(defaultStyle) |
| 110 | + final FontFamily family = familyBuilder.build(); |
| 111 | + return new Typeface.CustomFallbackBuilder(family) |
| 112 | + .setStyle(findBaseFont(family).getStyle()) |
97 | 113 | .build(); |
98 | 114 | } catch (Exception e) { |
99 | 115 | return null; |
@@ -128,14 +144,9 @@ public Typeface createFromFontFamilyFilesResourceEntry(Context context, |
128 | 144 | if (familyBuilder == null) { |
129 | 145 | return null; // No font is added. Give up. |
130 | 146 | } |
131 | | - final FontStyle defaultStyle = new FontStyle( |
132 | | - (style & Typeface.BOLD) != 0 ? FontStyle.FONT_WEIGHT_BOLD |
133 | | - : FontStyle.FONT_WEIGHT_NORMAL, |
134 | | - (style & Typeface.ITALIC) != 0 ? FontStyle.FONT_SLANT_ITALIC |
135 | | - : FontStyle.FONT_SLANT_UPRIGHT |
136 | | - ); |
137 | | - return new Typeface.CustomFallbackBuilder(familyBuilder.build()) |
138 | | - .setStyle(defaultStyle) |
| 147 | + final FontFamily family = familyBuilder.build(); |
| 148 | + return new Typeface.CustomFallbackBuilder(family) |
| 149 | + .setStyle(findBaseFont(family).getStyle()) |
139 | 150 | .build(); |
140 | 151 | } catch (Exception e) { |
141 | 152 | return null; |
|
0 commit comments