Html.ImageGetter

前端 未结 4 1232
暖寄归人
暖寄归人 2020-11-29 03:32

Can any one help me out how to use Html.ImageGetter to dispaly images using html image src tag ? and example or good tutorial

相关标签:
4条回答
  • 2020-11-29 04:08

    To get images from the application resources first in the text file one inserts an html image tag like this:

    <img src="my_image">
    

    Note that "my_image" is just a name of a drawable not a path. Then use this code to diplay the text with images in TextView

    myTextView.setText(Html.fromHtml(myText, new ImageGetter() {
       @Override public Drawable getDrawable(String source) {
          Drawable drawFromPath;
          int path =
                myActivity.this.getResources().getIdentifier(source, "drawable",
                   "com.package...");
          drawFromPath = myActivity.this.getResources().getDrawable(path);
          drawFromPath.setBounds(0, 0, drawFromPath.getIntrinsicWidth(),
             drawFromPath.getIntrinsicHeight());
          return drawFromPath;
       }
    }, null));
    

    If the source in the img tag is misspelled the applicaiton will crash because the method will fail to find the drawable, so more code can be added to prevent this...

    0 讨论(0)
  • 2020-11-29 04:08

    The answer from kape123 certainly helped me. I was so nearly there.

    The bit that's easy to miss is the call to setBounds on the Drawable. The Html.ImageGetter help documentation also provides a clue when it says:

    Make sure you call setBounds() on your Drawable if it doesn't already have its bounds set.

    0 讨论(0)
  • 2020-11-29 04:08
    textView.setText(Html.fromHtml(htmlToSetAsText, new ImageGetter() {                 
        @Override
        public Drawable getDrawable(String source) {
            String path = "/sdcard/" + source;
            Drawable bmp = Drawable.createFromPath(path);
            bmp.setBounds(0, 0, bmp.getIntrinsicWidth(), bmp.getIntrinsicHeight());
    
            return bmp;
        }
    }, null));
    
    0 讨论(0)
  • 2020-11-29 04:28

    Here is the same as the accepted answer, but as a top level class (which is nicer if you want to use it from different places):

    public class ResourceImageGetter implements ImageGetter {
        private Context mContext;
    
        public ResourceImageGetter(Context context) {
            mContext = context;
        }
    
        @Override
        public Drawable getDrawable(String source) {
            Resources resources = mContext.getResources();
            int identifier = resources.getIdentifier(source, "drawable", mContext.getPackageName());
            Drawable res = resources.getDrawable(identifier);
            res.setBounds(0, 0, res.getIntrinsicWidth(), res.getIntrinsicHeight());
            return res;
        }
    }
    
    0 讨论(0)
提交回复
热议问题