Android:EditText插入图片实现图文混排

2016年03月17日 Android 8条评论 阅读12906次


Android:多行EditText打造图文混排富文本编辑器


对于插入到富文本编辑框多行EditText的图片而言,什么样的尺寸都有可能出现,或者尺寸很大,或尺寸很小。对于这种情况,出于下面两点考虑,要做相应的优化。

  • 根据用户体验至上的原则,尽量不出现水平方向的滚动条,上下方向滚动条是可以接受的
  • Android设备中很大的图片会出现OOM的异常

所以我们的优化方案就出来了:

  • 如果插入图片的宽度大于EditText控件的宽度,按照EditText控件宽度的80%作为目标宽度,对原图进行压缩
  • 如果插入图片的宽度不大于EditText控件的宽度,则直接插入原图(不进行压缩)

Activity显示时,先获得插入图片的宽度,这里用EditText控件宽度的80%(考虑到两边留一些空白更更好看一些)作为插入图片的目标宽度

点击插入图片按钮时的响应时间

public void add_img(View v) {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, PICK_PIC);
} 

从图库选择一张图之后的处理逻辑

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == PICK_PIC) {
            if (data == null) {
                Toast.makeText(this, "failed", Toast.LENGTH_SHORT).show();
            } else {
                Uri uri = data.getData();
                Bitmap bitmap = getOriginalBitmap(uri);
                SpannableString ss = getBitmapMime(bitmap, uri);
                insertIntoEditText(ss);
            }
        }
    }
} 

其他关联代码

/**
 * EditText中可以接收的图片(要转化为SpannableString)
 * 
 * @param pic
 * @param uri
 * @return SpannableString
 */
private SpannableString getBitmapMime(Bitmap pic, Uri uri) {
    int imgWidth = pic.getWidth();
    int imgHeight = pic.getHeight();
    // 只对大尺寸图片进行下面的压缩,小尺寸图片使用原图
    if (imgWidth >= mInsertedImgWidth) {
        float scale = (float) mInsertedImgWidth / imgWidth;
        Matrix mx = new Matrix();
        mx.setScale(scale, scale);
        pic = Bitmap.createBitmap(pic, 0, 0, imgWidth, imgHeight, mx, true);
    }
    String smile = uri.getPath();
    SpannableString ss = new SpannableString(smile);
    ImageSpan span = new ImageSpan(this, pic);
    ss.setSpan(span, 0, smile.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ss;
}
private void insertIntoEditText(SpannableString ss) {
    // 先获取Edittext中原有的内容
    Editable et = et_addimage.getText();
    int start = et_addimage.getSelectionStart();
    // 设置ss要添加的位置
    et.insert(start, ss);
    // 把et添加到Edittext中
    et_addimage.setText(et);
    // 设置Edittext光标在最后显示
    et_addimage.setSelection(start + ss.length());
}
private Bitmap getOriginalBitmap(Uri photoUri) {
    if (photoUri == null) {
        return null;
    }
    Bitmap bitmap = null;
    try {
        ContentResolver conReslv = getContentResolver();
        // 得到选择图片的Bitmap对象
        bitmap = MediaStore.Images.Media.getBitmap(conReslv, photoUri);
    } catch (Exception e) {
        Log.e(TAG, "Media.getBitmap failed", e);
    }
    return bitmap;
} 

遇到的一些小问题

得到布局中EditText控件的宽度,使用ViewTreeObserver

ViewTreeObserver vto = et_addimage.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        et_addimage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        mImgViewWidth = et_addimage.getWidth();
        mInsertedImgWidth = mImgViewWidth * 0.8f;
    }
}); 

多行EditText的默认初始光标不在左上角

因为EditText默认的android:gravity属性值为center,在布局文件中把它改为top就可以了。

android:gravity="top" 

EditText,SpannableString insert-image-to-edittext

分享本文至:

WRITTEN BY

avatar
本文标签:EditText图文混排
看了本文是不是觉得很赞,那就赶紧点击下面按钮分享给身边的朋友吧!

8 条评论

  1. avatar hkyahao

    <a href="http://www.sohbetikiz.com/nike-free-3.0-focfly-so-barato-years-runninga">nike free 3.0 focfly so barato years</a> <a href="http://www.akkordiki.com/air-jordan-retro-12-cioccolato-scarpee">air jordan retro 12 cioccolato</a> <a href="http://www.torrentslot.com/nike-air-max-90-hyperfuse-oransje-lilla-runningg">nike air max 90 hyperfuse oransje lilla</a> <a href="http://www.familycarepc.com/nike-air-max-tailwind-8-dam%C3%A4nner-schwarz-schuhei">nike air max tailwind 8 dam盲nner schwarz</a> <a href="http://www.alizatrade.com/volcom-outdoors-snapback-cap-hath">volcom outdoors snapback cap</a> <a href="http://www.auroragenri.com/p%C3%BArpura-nike-huarache-basebtodas-cleats-trainersce">p煤rpura nike huarache basebtodas cleats</a>
    hkyahao http://www.hkyahao.com/

  2. avatar pragaoviedo

    <a href="http://www.teddevans.com/nike-dunk-high-hellboy-rot-schuhej">nike dunk high hellboy rot</a> <a href="http://www.cateycontrols.com/nike-sb-stefan-janoski-max-trainers-in-grau-schuhei">nike sb stefan janoski max trainers in grau</a> <a href="http://www.prodomfactory.com/air-jordan-cp3-svart-r%C3%B8d-obuvj">air jordan cp3 svart r酶d</a> <a href="http://www.tonyaespinoza.com/nike-flyknit-air-vapormax-2018-viola-bianca-scarpel">nike flyknit air vapormax 2018 viola bianca</a> <a href="http://www.nemagrp.com/femmes-marine-bleu-converse-chaussures-chaussuresh">femmes marine bleu converse chaussures</a> <a href="http://www.viajesclic.com/tutti-bianca-pelle-nike-shox-scarpeh">tutti bianca pelle nike shox</a>
    pragaoviedo http://www.pragaoviedo.com/

  3. avatar merleflugge

    <a href="http://www.bowtieorg.com/nike-air-max-lebron-8-all-black-shoesl">nike air max lebron 8 all black</a> <a href="http://www.shaneboothmx.com/ralph-lauren-equestrian-handbag-poloh">ralph lauren equestrian handbag</a> <a href="http://www.basarancarpet.com/nike-elastico-superfly-ic-gul-gr%C3%B8n-sort-skok">nike elastico superfly ic gul gr酶n sort</a> <a href="http://www.freedhamaal.com/nike-air-max-90-hyperfuse-herren-rot-schuheh">nike air max 90 hyperfuse herren rot</a> <a href="http://www.borbonecoffe.com/men-nike-air-max-tailwind-7-black-blue-white-shoesk">men nike air max tailwind 7 black blue white</a> <a href="http://www.cammaara.com/alle-hvid-nike-shox-herre-skol">alle hvid nike shox herre</a>
    merleflugge http://www.merleflugge.com/

  4. avatar converse salg rosa

    <a href="http://www.ankaraoyunevi.com/jordan-v5-grown-canvas-low-svart-obuvi">jordan v5 grown canvas low svart</a> <a href="http://www.iotlsebring.com/nike-huarache-r%C3%B8d-gr%C3%A5-svart-obuvk">nike huarache r酶d gr氓 svart</a> <a href="http://www.joshsingleton.com/nike-tiempo-legend-v-r%C3%B8d-hvit-obuvi">nike tiempo legend v r酶d hvit</a> <a href="http://www.amesecolombia.com/hombres-nike-air-huarache-negro-2-zapatosl">hombres nike air huarache negro 2</a> <a href="http://www.flatshotgame.com/nike-tiempo-legend-arancia-and-bianca-scarpeh">nike tiempo legend arancia and bianca</a> <a href="http://www.myrumpun.com/nike-cortez-nylon-men-camo-red-shoesk">nike cortez nylon men camo red</a>
    converse salg rosa http://www.actuelvet.com/converse-salg-rosa-obuvi

  5. avatar nchfnj

    <a href="http://www.magnindesign.com/stephen-curry-one-sko-for-salg-runningd">stephen curry one sko for salg</a> <a href="http://www.spinecareuk.com/rob-gronkowski-arizona-jersey-nflh">rob gronkowski arizona jersey</a> <a href="http://www.danteb.com/nike-air-max-2014-azul-zapatosh">nike air max 2014 azul</a> <a href="http://www.karlisteffy.com/nike-air-max-tailwind-5-oransje-lilla-scarpea">nike air max tailwind 5 oransje lilla</a> <a href="http://www.festadoano.com/golden-state-warriors-new-era-nba-retro-word-9fifty-snapback-cap-hati">golden state warriors new era nba retro word 9fifty snapback cap</a> <a href="http://www.bursagti.com/nike-air-max-chase-l%C3%A6der-trainersb">nike air max chase l忙der</a>
    nchfnj http://www.nchfnj.com/

  6. avatar lintvan

    <a href="http://www.rcrocs.com/ray-ban-classic-wayfarer-xl-sunglassesh">ray ban classic wayfarer xl</a> <a href="http://www.moreheaddotts.com/nike-air-huarache-noir-blanc-noir-chaussuresl">nike air huarache noir blanc noir</a> <a href="http://www.qgchsmrt.com/adidas-neo-blanc-philippines-chaussuresl">adidas neo blanc philippines</a> <a href="http://www.firagandia.com/dam%C3%A4nner-air-jordan-retro-13-wei%C3%9F-rosa-schuhej">dam盲nner air jordan retro 13 wei脽 rosa</a> <a href="http://www.lmladeco.com/dam%C3%A4nner-nike-air-max-90-wei%C3%9F-schuhei">dam盲nner nike air max 90 wei脽</a> <a href="http://www.brinkmanmdc.com/air-max-nike-sko-svart-obuvj">air max nike sko svart</a>
    [url=http://www.lintvan.com/]lintvan[/url]

  7. avatar eisenhards

    <a href="http://www.avantajreyonu.com/nike-tiempo-legend-v-grey-shoesk">nike tiempo legend v grey</a> <a href="http://www.oranjeskishop.com/ray-ban-justin-rubber-havana-sunglassesh">ray ban justin rubber havana</a> <a href="http://www.johannafrost.com/nike-sock-dart-sp-hommes-rose-chaussuresl">nike sock dart sp hommes rose</a> <a href="http://www.rolandviet.com/nike-kyrie-4-femmes-year-of-the-monkey-chaussuresl">nike kyrie 4 femmes year of the monkey</a> <a href="http://www.classmedya.com/frau-nike-kyrie-3-schwarz-wei%C3%9F-schuhej">frau nike kyrie 3 schwarz wei脽</a> <a href="http://www.anteageserums.com/supreme-x-nike-blazer-low-rosa-schuhei">supreme x nike blazer low rosa</a>
    eisenhards http://www.eisenhards.com/

  8. avatar 乐悠游

    有兴趣玩玩,收下这个,谢谢

欢迎留言




用户登录

sitemap