在android中,要明确一点,图片占用的内存大小与图片的实际大小无关,只与图片的分辨率有关,图片占用的内存空间为 图片分辨率 (高*宽)*4byte。
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/bt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="加载大图片"/> <ImageView android:id="@+id/iv" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
实现代码
package cn.test.ning.imagedemo; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { private ImageView iv; private Button bt; private int screenWidth; private int screenHight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bigimage); //获取屏幕信息 WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); //获取屏幕宽度 screenWidth = windowManager.getDefaultDisplay().getWidth(); //获取屏幕高度 screenHight = windowManager.getDefaultDisplay().getHeight(); iv = (ImageView) this.findViewById(R.id.iv); // Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); // iv.setImageBitmap(bitmap); bt = (Button) this.findViewById(R.id.bt); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.very_large_photo); BitmapFactory.Options opts = new BitmapFactory.Options(); //不真实的解析位图,只是返回位图的相关信息 opts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.very_large_photo,opts); int width = opts.outWidth;//图片的宽度 int higth = opts.outHeight;//图片的高度 //计算缩放比 int scale = 1; int scaleX = width /screenWidth; int scaleY = higth /screenHight; scale = (scaleX>scaleY?scaleX:scaleY); if (scale<1){ scale = 1; } //设置图片的缩放比 opts.inSampleSize = scale; //真实解析位图 opts.inJustDecodeBounds = false; //加载图片 重要的步骤 bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.very_large_photo,opts); iv.setImageBitmap(bitmap); } }); } }
使用到的图片