繁体   English   中英

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

[英]How to support italic font and bold font for Chinese

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

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

我假设你使用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);
    }
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM