簡體   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