圖文混排的幾種實現方案


1、自定義控件

https://github.com/hongyangAndroid/MixtureTextView

原理:MixtureTextView extends RelativeLayout,將圖片(包括gif)放在MixtureTextView中,根據屬性,例如alignParentRight等,在onLayout里獲取屬性值,在dispatchDraw里根據圖片所占的位置繪制文字,以此實現圖文混排

不足:圖片位置需要相對文字固定

 

2、使用html的img標簽實現

    /**
     * 拼接圖片
     *
     * @return
     */
    private String descString(String s) {
        return s + "<img src='" + R.drawable.icon + "'/>";
    }

 

tv_title.setText(Html.fromHtml(descString(bean.title), getImageGetterInstance(), null));

 

    /**
     * ImageGetter用於text圖文混排
     *
     * @return
     */
    public Html.ImageGetter getImageGetterInstance() {
        Html.ImageGetter imgGetter = new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {

                int fontH = (int) (getResources().getDimension(R.dimen.fontH));
                int id = Integer.parseInt(source);
                Drawable d = getResources().getDrawable(id);
                int width = (int) ((float) d.getIntrinsicWidth() / (float) d.getIntrinsicHeight()) * fontH;
                d.setBounds(0, 0, width, fontH);
                return d;
            }
        };
        return imgGetter;
    }

 優點:簡單,易使用

 不足:圖片位置適配不好處理(通過html標簽應該可以解決)

 

3、使用字體包ttf

原理:將圖案做在ttf里

string.xml,由設計給具體code

        <string name="fa_dot_circle_o">&#xf192;</string>
        <string name="fa_wheelchair">&#xf193;</string>
        <string name="fa_vimeo_square">&#xf194; &#xf195;</string>
        <string name="fa_try">&#xf195;</string>
        <string name="fa_plus_square_o">&#xf196;</string>

<string name="fa_dot_circle_o">&#xf192;</string>
<string name="fa_wheelchair">&#xf193;</string>
<string name="fa_vimeo_square">&#xf194; &#xf195;</string>
<string name="fa_try">&#xf195;</string>
<string name="fa_plus_square_o">&#xf196;</string>

 

textView直接引用

        Typeface font = Typeface.createFromAsset(getAssets(),
                "fontawesome-webfont.ttf");
        tab1.setTypeface(font);

 空格需要使用轉義字符

    public static String blankSpace =  "<font color=\"" + 0xff0000 + "\">&nbsp&nbsp</font>";
    public static String blankSpace2 =  "<font color=\"" + 0xff0000 + "\">&emsp&emsp</font>";

 優點:十分簡單

 不足:圖片顏色只能設置單一色


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM