AI智能
改变未来

android 缩放加载大图片


读取 sd卡大图片并且 缩放图片

1.添加权限

<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />

2.动态获取权限

ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

3.获取手机宽高

//获取手机分辨率 windowmanagerDisplayMetrics outMetrics = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(outMetrics);int widthPixels = outMetrics.widthPixels;int heightPixels = outMetrics.heightPixels;Log.i(\"MainActivity\", \"widthPixels = \" + widthPixels + \",heightPixels = \" + heightPixels);

4.实现缩放

//创建一个位图工厂的配置参数BitmapFactory.Options options = new BitmapFactory.Options();// 解析器不去真正的解析位图, 但是还能够获取图片的宽和高信息options.inJustDecodeBounds = true;BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + \"/aa.jpg\", options);int outWidth = options.outWidth;int outHeight = options.outHeight;Log.i(\"MainActivity\", \"图片的宽度: \" + outWidth + \" 图片的宽度:\" + outHeight);//计算缩放比例int scale = 1;int scaleX = outWidth / widthPixels;int scaleY = outHeight / heightPixels;//用大的比例缩放 scaleX>scale 缩放比大于1时候才需要缩放if (scaleX >= scaleY && scaleX > scale) {scale = scaleX;}if (scaleY > scaleX && scaleY > scale) {scale = scaleY;}//按照缩放比进行显示options.inSampleSize = scale;//按照缩放比 进行解析位图options.inJustDecodeBounds = false;Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + \"/aa.jpg\", options);imageView.setImageBitmap(bitmap);
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » android 缩放加载大图片