复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24/** * 将本地文件转换为 Drawable */ private Drawable iconDrawable(String file) { if (file == null || file.isEmpty()) { return null; } Drawable drawable = null; try { FileInputStream fis = new FileInputStream(file); Bitmap bitmap = BitmapFactory.decodeStream(fis); drawable = new BitmapDrawable(getResources(), bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } return drawable; }
或者直接利用:Bitmap bitmap = BitmapFactory.decodeFile(file); 获取 Bitmap,再构造出 Drawable。
说到 Bitmap,顺便讲一下Bitmap 改变图片尺寸的方法:
下面例子是从 assets 目录下读取图片文件,并支持改变图片尺寸返回 Bitmap
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46/** * 将 assets 下的图片转换为 Bitmap * @param fileName -- assets 下图片文件 * @param dst_w -- 输出宽度(为 0 时原图尺寸输出) * @param dst_h -- 输出高度(为 0 时原图尺寸输出) * @return Bitmap 图片 * 说明: * dst_w / dst_h 任意一值为 0 时,原图尺寸输出 */ private Bitmap imageFromAssetFile(String fileName, int dst_w, int dst_h) { Bitmap image = null; try { AssetManager am = getResources().getAssets(); InputStream is = am.open(fileName); if (is != null) { image = BitmapFactory.decodeStream(is); is.close(); } } catch (Exception e) { } if (dst_w == 0 || dst_h == 0) { return image; } if (image == null) { return null; } // 调整图片大小 int src_w = image.getWidth(); int src_h = image.getHeight(); float scale_w = ((float)dst_w) / src_w; float scale_h = ((float)dst_h) / src_h; Matrix matrix = new Matrix(); matrix.postScale(scale_w, scale_h); return Bitmap.createBitmap(image, 0, 0, src_w, src_h, matrix, true); }
最后
以上就是英勇超短裙最近收集整理的关于本地文件转 Drawable的全部内容,更多相关本地文件转内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复