缩放图片并加载到内存中
/**
1. 图片的宽高
2. 获取手机屏幕的宽高
3. 计算合适的缩放比例
4. 显示缩放图片
*/
import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.os.Bundle; import android.view.Display; import android.view.WindowManager; import android.widget.ImageView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView iv = (ImageView) findViewById(R.id.iv); Options opt = new Options(); //只拿图片的宽高,不加载图片 opt.inJustDecodeBounds = true; BitmapFactory.decodeFile("/mnt/sdcard/dog.jpg",opt); //图片的宽高 int pHeight = opt.outHeight; int pWidth = opt.outWidth; //获取手机屏幕的宽高 WindowManager wm=(WindowManager)getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); int sWidth = display.getWidth(); int sHeight = display.getHeight(); //计算合适的缩放比例 int width = pWidth / sWidth; int height = pHeight / sHeight; int scale = 1; if (width >= height && width > 1) { scale = width; }else if(height > width && height >1) { scale = height; } //显示缩放图片 opt.inJustDecodeBounds = false; //设置缩放的比例值 opt.inSampleSize = scale; Bitmap bmp = BitmapFactory.decodeFile("/mnt/sdcard/dog.jpg",opt); iv.setImageBitmap(bmp); } }
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!