Android 图文混排(一) TextView实现图文显示

总体思路如下:

在 TextView 中显示图片,可以使用Html.fromHtml(source, imageGetter, tagHandler)通过自定义imageGetter来异步加载图片,最后完成图文混排。

1、自定义imageGetter

public class UrlImageGetter implements ImageGetter {
    @Overridepublic Drawable getDrawable(String source) {
        return null;
    }
}

继承ImageGetter实现里面的getDrawable方法。
在getDrawable中的source就是 img标签里src的值也就是图片的路径。

我们使用universal-image-loader.jar来异步加载这些图片

ImageLoader.getInstance().loadImage(source, new SimpleImageLoadingListener() {
        @Overridepublic void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                
        }
});

2、因为图片是异步加载的,所以我们要先建立一个BitmapDrawable,当没有异步加载的时候用来getDrawable的返回

public class UrlDrawable extends BitmapDrawable {
    protected Bitmap bitmap;
    @Override
    public void draw(Canvas canvas) {
        // override the draw to facilitate refresh function later
        if (bitmap != null) {
            canvas.drawBitmap(bitmap, 0, 0, getPaint());
        }
    }
}

在异步加载成功设置监听,成功的时候,我们把BitmapDrawable的bitmap赋上我们异步得到的Bitmap对象在重新绘制,就可以显示出图片,由于图片可能没有固定的尺寸,为了美观我们同意把图片的宽度设置成和手机屏幕的宽度一致
具体代码如下:

ImageLoader.getInstance().loadImage(source, new SimpleImageLoadingListener() {
    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        // 计算缩放比例
        float scaleWidth = ((float) width)/loadedImage.getWidth();
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleWidth);
        loadedImage = Bitmap.createBitmap(loadedImage, 0, 0, loadedImage.getWidth(), loadedImage.getHeight(), matrix,                true);
        urlDrawable.bitmap = loadedImage;
        urlDrawable.setBounds(0, 0, loadedImage.getWidth(), loadedImage.getHeight());
        container.invalidate();
        container.setText(container.getText()); // 解决图文重叠
    }
});

效果图如下:

Android 图文混排(一) TextView实现图文显示_第1张图片
效果图

最后发上代码
HtmlTextView.java

public class HtmlTextView extends TextView {
    public static final String TAG = "HtmlTextView";
    public static final boolean DEBUG = false;

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

    public HtmlTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HtmlTextView(Context context) {
        super(context);
    }

    /**
     * @param is
     * @return
     */
    static private String convertStreamToString(InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");

        return s.hasNext() ? s.next() : "";
    }

    /**
     * Parses String containing HTML to Android's Spannable format and displays
     * it in this TextView.
     *
     * @param html String containing HTML, for example: "Hello world!"
     */
    public void setHtmlFromString(String html, boolean useLocalDrawables) {
        Html.ImageGetter imgGetter;

        if (useLocalDrawables) {
            imgGetter = new LocalImageGetter(getContext());
        } else {
            imgGetter = new UrlImageGetter(this, getContext());
        }

        // this uses Android's Html class for basic parsing, and HtmlTagHandler
        setText(Html.fromHtml(html, imgGetter, new HtmlTagHandler()));

        // make links work
        setMovementMethod(LinkMovementMethod.getInstance());
        text.setTextColor(getResources().getColor(android.R.color.secondary_text_dark_nodisable));
    }
}

UrlImageGetter.java

public class UrlImageGetter implements ImageGetter {
    Context c;
    TextView container;
    int width;

    /**
     *
     * @param t
     * @param c
     */
    public UrlImageGetter(TextView t, Context c) {
        this.c = c;
        this.container = t;
        width = c.getResources().getDisplayMetrics().widthPixels;
    }

    @Override
    public Drawable getDrawable(String source) {
        final UrlDrawable urlDrawable = new UrlDrawable();
        ImageLoader.getInstance().loadImage(source,
            new SimpleImageLoadingListener() {
                @Override
                public void onLoadingComplete(String imageUri, View view,
                    Bitmap loadedImage) {
                    // ??????
                    float scaleWidth = ((float) width) / loadedImage.getWidth();

                    // ???????matrix??
                    Matrix matrix = new Matrix();
                    matrix.postScale(scaleWidth, scaleWidth);
                    loadedImage = Bitmap.createBitmap(loadedImage, 0, 0,
                            loadedImage.getWidth(), loadedImage.getHeight(),
                            matrix, true);
                    urlDrawable.bitmap = loadedImage;
                    urlDrawable.setBounds(0, 0, loadedImage.getWidth(),
                        loadedImage.getHeight());
                    container.invalidate();
                    container.setText(container.getText()); // ??????
                }
            });

        return urlDrawable;
    }

    @SuppressWarnings("deprecation")
    public class UrlDrawable extends BitmapDrawable {
        protected Bitmap bitmap;

        @Override
        public void draw(Canvas canvas) {
            // override the draw to facilitate refresh function later
            if (bitmap != null) {
                canvas.drawBitmap(bitmap, 0, 0, getPaint());
            }
        }
    }
}

最后的设置文本

String html = "下面是图片了 " +"src='http://www.qqpk.cn/Article/UploadFiles/201411/20141116135722282.jpg'/>" +
        "这也是图片" +"src='http://h.hiphotos.baidu.com/image/pic/item/d000baa1cd11728b2027e428cafcc3cec3fd2cb5.jpg'/>" +
        "还有一张"+  "src='http://img.61gequ.com/allimg/2011-4/201142614314278502.jpg' />";

private HtmlTextView main;
@Overrideprotected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    main = (HtmlTextView) this.findViewById(R.id.main_text);
    main.setHtmlFromString(html,false);
}

请在scr 前补上

markdown会把img标签转成图片,️知道的望告知怎么破

如有什么不对或者不规范的地方请留言或私信我,非常感谢

传送门:
1、Android 图文混排(一) TextView实现图文显示
2、Android 图文混排(二) EditText实现图文显示
3、Android 图文混排(三)TextView图片点击

你可能感兴趣的:(Android 图文混排(一) TextView实现图文显示)