android 加载图片
16lz
2021-01-23
.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); } }
更多相关文章
- Android中拍照、图片、录音、视频和音频功能的方法和代码
- Android之获取加载图片宽高问题(getIntrinsicWidth与getwidth的区
- Android HorizontalScrollView 水平滑动 在listview上面动态添加
- Android使用JPEG实现图片压缩上传
- Android 保存图片到相册无法显示的问题
- Android获取SD卡上图片和视频文件及其缩略图
- Android 代码修改按钮上的图片
- Android Bitmap 缩放 旋转 水印 裁剪操作
- Android实现网络图片查看器和网页源码查看器