如何支持中文的斜体字体和粗体字体

时间:2011-11-24 10:01:34

标签: android fonts

我的Android应用程序将使用中文。常规字体是正常的,但斜体字体和粗体字体不起作用。

那么我应该使用哪些字体文件用于中文斜体和粗体字?

2 个答案:

答案 0 :(得分:4)

我假设您使用TextView来显示中文字词。

如果您希望TextView中的任何单词都是粗体或斜体,那么这将很容易。 只需使用

testView.getPaint().setFakeBoldText(true);

使所有单词都变粗。

斜体,请使用:

testView.getPaint().setTextSkewX(-0.25f);

但是,如果您只想要一些粗体或斜体字。通常情况下,您可以在StyleSpan的特定范围内设置Spannable,但这不适用于中文字。

因此,我建议您创建一个扩展StyleSpan

的类
public class ChineseStyleSpan extends StyleSpan{
    public ChineseStyleSpan(int src) {
        super(src);

    }
    public ChineseStyleSpan(Parcel src) {
        super(src);
    }
    @Override
    public void updateDrawState(TextPaint ds) {
        newApply(ds, this.getStyle());
    }
    @Override
    public void updateMeasureState(TextPaint paint) {
        newApply(paint, this.getStyle());
    }

    private static void newApply(Paint paint, int style){
        int oldStyle;

        Typeface old = paint.getTypeface();
        if(old == null)oldStyle =0;
        else oldStyle = old.getStyle();

        int want = oldStyle | style;
        Typeface tf;
        if(old == null)tf = Typeface.defaultFromStyle(want);
        else tf = Typeface.create(old, want);
        int fake = want & ~tf.getStyle(); 

        if ((want & Typeface.BOLD) != 0)paint.setFakeBoldText(true);
        if ((want & Typeface.ITALIC) != 0)paint.setTextSkewX(-0.25f); 
        //The only two lines to be changed, the normal StyleSpan will set you paint to use FakeBold when you want Bold Style but the Typeface return say it don't support it.
        //However, Chinese words in Android are not bold EVEN THOUGH the typeface return it can bold, so the Chinese with StyleSpan(Bold Style) do not bold at all.
        //This Custom Class therefore set the paint FakeBold no matter typeface return it can support bold or not.
        //Italic words would be the same

        paint.setTypeface(tf);
    }
}

将此范围设为您的中文单词,我应该工作。 请注意检查它仅适用于中文单词。我没有对它进行测试,但我可以想象,在大胆的英文字符上设置假冒伪劣版本会非常难看。

答案 1 :(得分:1)

我建议你在显示中文文字时不要使用粗体斜体字体。

粗体可能会扭曲文本,而斜体只会人为地扭曲文本。