Android TextView顯示圖片的三種方法

方法一:重寫TextView的onDraw方法,也挺直觀就是不太好控制顯示完 圖片後再顯示字體所佔空間的位置關係。


效果圖:


自定義View代碼如下:

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;
/**
 * @author Demon
 */
public class TextViewImage_1 extends TextView{
    private Drawable exampleDrawable;

    private TextPaint textPaint;
    private float textHeight;

    public TextViewImage_1(Context context) {
        super(context);
        init(null, 0);
    }

    public TextViewImage_1(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public TextViewImage_1(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle) {
        // Load attributes
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.TextViewImage_1, defStyle, 0);

        if (a.hasValue(R.styleable.TextViewImage_1_exampleDrawable)) {
            exampleDrawable = a.getDrawable(
                    R.styleable.TextViewImage_1_exampleDrawable);
            assert exampleDrawable != null;
            exampleDrawable.setCallback(this);
        }

        a.recycle();

        // Set up a default TextPaint object
        textPaint = new TextPaint();
        textPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextAlign(Paint.Align.LEFT);

        // Update TextPaint and text measurements from attributes
        invalidateTextPaintAndMeasurements();
    }

    private void invalidateTextPaintAndMeasurements() {

        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        textHeight = fontMetrics.bottom;
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);

        // allocations per draw cycle.
        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        int paddingRight = getPaddingRight();
        int paddingBottom = getPaddingBottom();

        // Draw the example drawable on top of the text.
        if (exampleDrawable != null) {
            int contentWidth = getWidth()- paddingLeft - paddingRight;
            int contentHeight = getHeight() - paddingTop - paddingBottom;
            exampleDrawable.setBounds(paddingLeft, paddingTop,
                    paddingLeft + contentWidth, paddingTop + contentHeight);
            exampleDrawable.draw(canvas);
        }
    }


    /**
     * Gets the example drawable attribute value.
     *
     * @return The example drawable attribute value.
     */
    public Drawable getExampleDrawable() {
        return exampleDrawable;
    }

    /**
     * Sets the view's example drawable attribute value. In the example view, this drawable is
     * drawn above the text.
     *
     * @param exampleDrawable The example drawable attribute value to use.
     */
    public void setExampleDrawable(Drawable exampleDrawable) {
        exampleDrawable = exampleDrawable;
    }

xml文件引用:

<bingyan.net.textimage.TextViewImage_1
        android:background="#ffff00" android:layout_width="300dp"
        android:layout_height="300dp"
        app:exampleDrawable="@mipmap/ic_launcher"
        android:id="@+id/textView_image"/>

方法二:利用TextView支持部分Html的特性,直接用api賦圖片。

效果圖如下


代碼段如下:

String html = "<img src='" + R.mipmap.ic_launcher + "'/>";
Html.ImageGetter imageGetter = new Html.ImageGetter() {
/*
* This method is called when the HTML parser encounters an <img> tag.
* The source argument is the string from the "src" attribute;
* the return value should be a Drawable representation of the image or null for a generic replacement image.
* Make sure you call setBounds() on your Drawable if it doesn't already have its bounds set.*/
    @Override
    public Drawable getDrawable(String source) {
        int id = Integer.parseInt(source);
        Drawable src = getResources().getDrawable(id);
        src.setBounds(0, 0, src.getIntrinsicWidth(), src.getIntrinsicHeight());
        return src;
    }
        };
CharSequence charSequence = Html.fromHtml(html, imageGetter, null);
textView.setText(charSequence);
textView.append("Hello,this is demon");

方法三: 用ImageSpan和SpannableString


效果圖:


代碼塊:

Bitmap b = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
ImageSpan imgSpan = new ImageSpan(this, b);
SpannableString spanString = new SpannableString("icon"+"這裏的文字沒有被覆蓋");
/*要讓圖片替代指定的文字就要用ImageSpan
*第2和第3個參數表示從哪裏開始替換到哪裏替換結束(start和end)
*/
spanString.setSpan(imgSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

其實SpannableString很強大,下面再來看下它的幾個常見用法


文本高亮:


代碼塊:

SpannableStringBuilder spannable=new SpannableStringBuilder("高亮文本");//用於可變字符串     
ForegroundColorSpan span=new ForegroundColorSpan(Color.WHITE);
spannable.setSpan(span, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);

加下劃線:


代碼塊:

 SpannableStringBuilder spannable=new SpannableStringBuilder("加下劃線文本");
CharacterStyle span=new UnderlineSpan();
spannable.setSpan(span, 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);

組合使用:


代碼塊:

 SpannableStringBuilder spannable=new SpannableStringBuilder("組合使用");
CharacterStyle span_1=new StyleSpan(android.graphics.Typeface.ITALIC);
CharacterStyle span_2=new ForegroundColorSpan(Color.RED);
spannable.setSpan(span_1, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(span_2, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);

有時需要將某關鍵字高亮:

最簡單的想法是用循環實現:

代碼塊:

String tmp = "bingyantestbingyantestbingyanbingyantestbingyanbingyanbingyan";
SpannableStringBuilder spannable = new SpannableStringBuilder(tmp);
String target = "bingyan";
CharacterStyle span;
Pattern pattern = Pattern.compile(target);
Matcher matcher = pattern.matcher(tmp);
while (matcher.find()) {
    span= new ForegroundColorSpan(Color.RED);
    spannable.setSpan(span, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
textView.setText(spannable);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章