Merge "Select closest font's style for backward compatibility"
This commit is contained in:
committed by
Android (Google) Code Review
commit
d380bd78bb
@@ -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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user