Merge "Select closest font's style for backward compatibility"

This commit is contained in:
TreeHugger Robot
2018-12-04 10:10:11 +00:00
committed by Android (Google) Code Review
3 changed files with 43 additions and 2 deletions

View File

@@ -660,7 +660,22 @@ public class FontsContract {
if (familyBuilder == null) {
return null;
}
return new Typeface.CustomFallbackBuilder(familyBuilder.build()).build();
final FontFamily family = familyBuilder.build();
final FontStyle normal = new FontStyle(FontStyle.FONT_WEIGHT_NORMAL,
FontStyle.FONT_SLANT_UPRIGHT);
Font bestFont = family.getFont(0);
int bestScore = normal.getMatchScore(bestFont.getStyle());
for (int i = 1; i < family.getSize(); ++i) {
final Font candidate = family.getFont(i);
final int score = normal.getMatchScore(candidate.getStyle());
if (score < bestScore) {
bestFont = candidate;
bestScore = score;
}
}
return new Typeface.CustomFallbackBuilder(family).setStyle(bestFont.getStyle()).build();
}
/**

View File

@@ -249,7 +249,22 @@ public class Typeface {
if (familyBuilder == null) {
return Typeface.DEFAULT;
}
typeface = new Typeface.CustomFallbackBuilder(familyBuilder.build()).build();
final FontFamily family = familyBuilder.build();
final FontStyle normal = new FontStyle(FontStyle.FONT_WEIGHT_NORMAL,
FontStyle.FONT_SLANT_UPRIGHT);
Font bestFont = family.getFont(0);
int bestScore = normal.getMatchScore(bestFont.getStyle());
for (int i = 1; i < family.getSize(); ++i) {
final Font candidate = family.getFont(i);
final int score = normal.getMatchScore(candidate.getStyle());
if (score < bestScore) {
bestFont = candidate;
bestScore = score;
}
}
typeface = new Typeface.CustomFallbackBuilder(family)
.setStyle(bestFont.getStyle())
.build();
} catch (IOException e) {
typeface = Typeface.DEFAULT;
}

View File

@@ -18,6 +18,7 @@ package android.graphics.fonts;
import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import com.android.internal.util.Preconditions;
@@ -232,6 +233,16 @@ public final class FontStyle {
return mSlant;
}
/**
* Compute the matching score for another style.
*
* The smaller is better.
* @hide
*/
public int getMatchScore(@NonNull FontStyle o) {
return Math.abs((getWeight() - o.getWeight())) / 100 + (getSlant() == o.getSlant() ? 0 : 2);
}
@Override
public boolean equals(@Nullable Object o) {
if (o == this) {