.Android在加载大背景图或者大图片时,经常导致内存溢出(Out of Memory Error)

可们可能跟据imageView的宽高来对图片进行压缩,关效的解决(Out of Memory Error)

直接上代码 :

xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >          <ImageView       android:src="@drawable/ic_launcher"       android:id="@+id/image"       android:layout_height="fill_parent"       android:layout_width="fill_parent"       /> <Button        android:onClick="onClick"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></RelativeLayout>

java

    ImageView image;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        image=(ImageView) findViewById(R.id.image);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }        public void onClick(View view){    //解析图片时需要使用到的参数都封装在这个对象里了    Options opt = new Options();    //不为像素申请内存,只获取图片宽高    opt.inJustDecodeBounds = true;    BitmapFactory.decodeResource(getResources(), R.drawable.dog, opt);    //拿到图片宽高    int imageWidth = opt.outWidth;    int imageHeight = opt.outHeight;        Display dp = getWindowManager().getDefaultDisplay();    //拿到屏幕宽高int screenWidth = dp.getWidth();    int screenHeight = dp.getHeight();        //计算缩放比例    int scale = 1;    int scaleWidth = imageWidth / screenWidth;    int scaleHeight = imageHeight / screenHeight;            int max=Math.max(scaleWidth, scaleHeight);        if (max>scale) {    scale=max;}        //设置缩放比例    opt.inSampleSize = scale;    opt.inJustDecodeBounds = false;    Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.dog, opt);    image.setImageBitmap(bitmap);    }    }




更多相关文章

  1. Android中拍照、图片、录音、视频和音频功能的方法和代码
  2. Android之获取加载图片宽高问题(getIntrinsicWidth与getwidth的区
  3. Android HorizontalScrollView 水平滑动 在listview上面动态添加
  4. Android使用JPEG实现图片压缩上传
  5. Android 保存图片到相册无法显示的问题
  6. Android获取SD卡上图片和视频文件及其缩略图
  7. Android 代码修改按钮上的图片
  8. Android Bitmap 缩放 旋转 水印 裁剪操作
  9. Android实现网络图片查看器和网页源码查看器

随机推荐

  1. HTML常用标签
  2. 【案例】星环科技原厂数据备份恢复软件,让
  3. 【案例】星环智能分析工具 Sophon,助力上
  4. php在线生成ico文件的代码
  5. git 的入门使用到团队协作
  6. 关于网站链接使用相对路径还是绝对路径的
  7. 利用函数对对象的处理
  8. 深入浅出理解PHP原理之变量赋值
  9. 微信JSSDK签名
  10. 【前端】新手使用uikit-幻灯片,但是在播放