一起学习android图像缩放资源 (27)

时间:2021-08-10 05:17:59

效果图:

一起学习android图像缩放资源 (27)

在平时载入图片时,我会使用SetImageBitmap、setImageResource、BitmapFactory.decodeResource来设置一张图

片通过以上方法来设置图片时。会通过Java层的createBitmap来完毕。这种话会消耗非常多内存。easy导致

OOM(Out Of Memory),因此推荐使用BitmapFactory.Options这个类来设置一张资源图。

參看下面代码:

public class MainActivity extends Activity {
private ImageView imageView1;
private ImageView imageView2;
Bitmap mBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
initView(); } private void initView(){
imageView1=(ImageView)findViewById(R.id.imageView1);
imageView2=(ImageView)findViewById(R.id.imageView2);
//读取资源图片
mBitmap=readBitMap();
//对资源图片进行缩放
imageView2.setImageBitmap(zoomBitmap(mBitmap, mBitmap.getWidth()/4, mBitmap.getHeight()/4));
} /**
* 读取资源图片
* @return
*/
private Bitmap readBitMap(){
BitmapFactory.Options opt=new BitmapFactory.Options();
/*
* 设置让解码器以最佳方式解码
*/
opt.inPreferredConfig=Bitmap.Config.RGB_565;
//以下两个字段须要组合使用
opt.inPurgeable=true;
opt.inInputShareable=true;
/*
* 获取资源图片
*/
InputStream is=this.getResources().openRawResource(R.drawable.mei);
return BitmapFactory.decodeStream(is, null, opt);
} /**
* 缩放图片
* @param bitmap
* @param w
* @param h
* @return
*/
public Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidht = ((float) w / width);
float scaleHeight = ((float) h / height);
/*
* 通过Matrix类的postScale方法进行缩放
*/
matrix.postScale(scaleWidht, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
return newbmp;
} }

image.xml:

<?xml version="1.0" encoding="utf-8"?

>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/mei" /> <ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_below="@+id/imageView1"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:src="@drawable/mei" /> </RelativeLayout>

转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/44281087情绪控_

版权声明:本文博主原创文章,博客,未经同意不得转载。