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);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值