android应用中常常需要加载R.drawable下的图片资源到ImageView中显示出来。而且常常会遇到图片缩放的问题,缩放的关键是Matrix(矩阵方式)。加载资源图片以及缩放的语法是非常典型的一种写法,这里不妨把它记录下来:
加载图片
缩放图片
重点是获取源图片位图资源的语法:
[color=blue]bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.flower);[/color]
以及根据原始位图和缩放矩阵创造新图片的语法:
[color=blue]Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);[/color]
另外,获取ImageView组件内的BitmapDrawable:
[color=blue]BitmapDrawable tmp = (BitmapDrawable) imageView.getDrawable();[/color]
加载图片
//显示图片的ImageView组件
ImageView imageView;
//初始的图片资源
Bitmap bitmap;
//图片的宽和高、当前缩放比、控制缩放的矩阵
int width, height;
Matrix matrix;
float curScale = 1;
imageView = (ImageView) findViewById(R.id.image);
matrix = new Matrix();
//获取源图片
bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.flower);
//或者可以这样获取(不是从R.drawable.xx下加载时)
Bitmap bitmap = BitmapFactory.decodeFile(String pathName));
//获得位图宽和高
width = bitmap.getWidth();
height = bitmap.getHeight();
//设置imageview初始化时显示的图片
imageView.setImageBitmap(bitmap);
缩放图片
//重置matrix
matrix.reset();
//缩放matrix
matrix.setScale(curScale, curScale, 160, 200);
//根据原始位图和Matrix创建新图片
Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
//显示新的位图
imageView.setImageBitmap(bitmap2);
重点是获取源图片位图资源的语法:
[color=blue]bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.flower);[/color]
以及根据原始位图和缩放矩阵创造新图片的语法:
[color=blue]Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);[/color]
另外,获取ImageView组件内的BitmapDrawable:
[color=blue]BitmapDrawable tmp = (BitmapDrawable) imageView.getDrawable();[/color]