@RitcheeQinG
2020-03-23T08:52:03.000000Z
字数 1403
阅读 243
Android
经过测试,在TypefaceSpan里面设置bold的字体和用StyleSpan加上的bold效果应该是不同的,所以对于有的Typeface.create()无法创建的字体来说,就得想个别的办法
import android.content.res.Resources;import android.graphics.Typeface;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.support.v4.content.res.ResourcesCompat;import android.text.TextPaint;import android.text.style.TypefaceSpan;import com.xxx.xxx.R;public class CustomTypefaceSpan extends TypefaceSpan {public CustomTypefaceSpan(@Nullable String family) {super(family);}@Overridepublic void updateDrawState(@NonNull TextPaint paint) {int oldStyle;Typeface old = paint.getTypeface();if (old == null) {oldStyle = 0;} else {oldStyle = old.getStyle();}Typeface tf = Typeface.create(getFamily(), oldStyle);int resId = getResByName();if (-1 != resId) {try {tf = ResourcesCompat.getFont(getContext(), resId);} catch (Resources.NotFoundException e) {e.printStackTrace();}}if (null == tf) {tf = Typeface.create(getFamily(), oldStyle);}int fake = oldStyle & ~tf.getStyle();if ((fake & Typeface.BOLD) != 0) {paint.setFakeBoldText(true);}if ((fake & Typeface.ITALIC) != 0) {paint.setTextSkewX(-0.25f);}paint.setTypeface(tf);}private int getResByName() {String name = getFamily();if (null == name) {return -1;}switch (name) {case "gilroy_bold":return R.font.gilroy_bold;case "gilroy_semibold":return R.font.gilroy_semibold;case "gilroy_extrabold":return R.font.gilroy_extrabold;case "gilroy_medium":return R.font.gilroy_medium;default:return -1;}}}