2024年3月27日发(作者:)
在Android UI开发专题的前五节我们讲到的东西主要是基础和理论内容,从本次
Android123将通过实例代码来演示,本次主要是Bitmap和Canvas类的使用,根据要求缩
放Bitmap对象并返回新的Bitmap对象。centerToFit方法一共有4个参数,返回一个Bitmap
类型,第一个参数为原始的位图对象,width和height分别为新的宽和高,而Context是
用来加载资源的上下文实例。
1 Bitmap centerToFit(Bitmap bitmap, int width, int height, Context context) {
2
3 final int bitmapWidth = th(); //获取原始bitmap的宽度
4
5 final int bitmapHeight = ght();
6
7 if (bitmapWidth < width || bitmapHeight < height) {
8
9 int color = ources().getColor(_background); //
从资源读取背景色
10
11 Bitmap centered = Bitmap(bitmapWidth < width ? width : bitmap
Width,
12
13 bitmapHeight < height ? height : bitmapHeight, _565);
14
15 sity(sity());
16
17 Canvas canvas = new Canvas(centered);
18
19 lor(color); //先绘制背景色
20
21 tmap(bitmap, (width - bitmapWidth) / 2.0f, (height - bitmapHei
ght) / 2.0f,null); //通过Canvas绘制Bitmap
22
23 bitmap = centered;
24
25 }
26
27 return bitmap; //返回新的bitmap
28
29 }
30
31
本段代码从Android 2.1开始将会应用在全新的Home主屏上,同时相关的ImageView
的适应屏幕大小的setScaleType(fitCenter) 方法类似,仅仅是我们制定了未来的大小。


发布评论