现在在做一个便签,用到记录一下。
View Code
函数如下 //onActivityResult Uri uri=data.getData(); // 通过URI得到图片在系统的路径 // String[] proj = {MediaStore.Images.Media.DATA}; ////好像是android多媒体数据库的封装接口,具体的看Android文档 // Cursor cursor = managedQuery(uri, proj, null, null, null); ////按我个人理解 这个是获得用户选择的图片的索引值 // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); ////将光标移至开头 ,这个很重要,不小心很容易引起越界 // cursor.moveToFirst(); ////最后根据索引值获取图片路径 // String path = cursor.getString(column_index); Bitmap pic = null; pic = getBitmap(data.getData()); insertIntoEditText(getBitmapMime(pic, uri));
View Code
/** * 通过路径获取系统图片 * @param uri * @return */ private Bitmap getBitmap(Uri uri) { Bitmap pic = null; BitmapFactory.Options op = new BitmapFactory.Options(); op.inJustDecodeBounds = true; Display display = getWindowManager().getDefaultDisplay(); int dw = display.getWidth(); int dh = display.getHeight(); try { pic = BitmapFactory.decodeStream(getContentResolver() .openInputStream(uri), null, op); } catch (FileNotFoundException e) { e.printStackTrace(); } int wRatio = (int) Math.ceil(op.outWidth / (float) dw); int hRatio = (int) Math.ceil(op.outHeight / (float) dh); if (wRatio > 1 && hRatio > 1) { op.inSampleSize = wRatio + hRatio; } op.inJustDecodeBounds = false; try { pic = BitmapFactory.decodeStream(getContentResolver() .openInputStream(uri), null, op); } catch (FileNotFoundException e) { e.printStackTrace(); } return pic; } /** * 图片转成SpannableString加到EditText中 * * @param pic * @param uri * @return */ private SpannableString getBitmapMime(Bitmap pic, Uri uri) { // int imgWidth = pic.getWidth(); // int imgHeight = pic.getHeight(); // float scalew = (float) 40 / imgWidth; // float scaleh = (float) 40 / imgHeight; // Matrix mx = new Matrix(); // mx.setScale(scalew, scaleh); // 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) { Editable et = editText_Content.getText();// 先获取Edittext中的内容 int start = editText_Content.getSelectionStart(); et.insert(start, ss);// 设置ss要添加的位置 editText_Content.setText(et);// 把et添加到Edittext中 editText_Content.setSelection(start + ss.length());// 设置Edittext中光标在最后面显示 } }