[关闭]
@RitcheeQinG 2020-03-23T08:52:03.000000Z 字数 1403 阅读 214

自定义TypefaceSpan

Android


经过测试,在TypefaceSpan里面设置bold的字体和用StyleSpan加上的bold效果应该是不同的,所以对于有的Typeface.create()无法创建的字体来说,就得想个别的办法

  1. import android.content.res.Resources;
  2. import android.graphics.Typeface;
  3. import android.support.annotation.NonNull;
  4. import android.support.annotation.Nullable;
  5. import android.support.v4.content.res.ResourcesCompat;
  6. import android.text.TextPaint;
  7. import android.text.style.TypefaceSpan;
  8. import com.xxx.xxx.R;
  9. public class CustomTypefaceSpan extends TypefaceSpan {
  10. public CustomTypefaceSpan(@Nullable String family) {
  11. super(family);
  12. }
  13. @Override
  14. public void updateDrawState(@NonNull TextPaint paint) {
  15. int oldStyle;
  16. Typeface old = paint.getTypeface();
  17. if (old == null) {
  18. oldStyle = 0;
  19. } else {
  20. oldStyle = old.getStyle();
  21. }
  22. Typeface tf = Typeface.create(getFamily(), oldStyle);
  23. int resId = getResByName();
  24. if (-1 != resId) {
  25. try {
  26. tf = ResourcesCompat.getFont(getContext(), resId);
  27. } catch (Resources.NotFoundException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. if (null == tf) {
  32. tf = Typeface.create(getFamily(), oldStyle);
  33. }
  34. int fake = oldStyle & ~tf.getStyle();
  35. if ((fake & Typeface.BOLD) != 0) {
  36. paint.setFakeBoldText(true);
  37. }
  38. if ((fake & Typeface.ITALIC) != 0) {
  39. paint.setTextSkewX(-0.25f);
  40. }
  41. paint.setTypeface(tf);
  42. }
  43. private int getResByName() {
  44. String name = getFamily();
  45. if (null == name) {
  46. return -1;
  47. }
  48. switch (name) {
  49. case "gilroy_bold":
  50. return R.font.gilroy_bold;
  51. case "gilroy_semibold":
  52. return R.font.gilroy_semibold;
  53. case "gilroy_extrabold":
  54. return R.font.gilroy_extrabold;
  55. case "gilroy_medium":
  56. return R.font.gilroy_medium;
  57. default:
  58. return -1;
  59. }
  60. }
  61. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注