package com.itheima40.loadbigpic;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity {
private EditText etPath;
private ImageView ivIcon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//加载控件---获取输入路径的文本框和显示图片的ImageView
etPath = (EditText) findViewById(R.id.et_path);
ivIcon = (ImageView) findViewById(R.id.iv_icon);
}
//按钮的点击事件
/**
* 缩放加载
* @param v
*/
public void scaleLoad(View v) {
String path = etPath.getText().toString();
Options opts = new Options();
opts.inJustDecodeBounds = true; // 设置为true, 加载器不会返回图片, 而是把Options对象中以out开头的字段给设置了.
BitmapFactory.decodeFile(path, opts);
// 得到了图片的宽和高
int imageWidth = opts.outWidth;
int imageHeight = opts.outHeight;
System.out.println("图片的宽和高: " + imageWidth + " * " + imageHeight);
// 获取屏幕的宽和高
Display display = this.getWindowManager().getDefaultDisplay(); // 获取默认窗体显示的对象
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
System.out.println("屏幕的宽和高: " + screenWidth + " * " + screenHeight);
// 计算缩放比例
int widthScale = imageWidth / screenWidth;
int heightScale = imageHeight / screenHeight;
//选择比例大的那个进行缩放
int scale = widthScale > heightScale ? widthScale:heightScale;
System.out.println("缩放比例: " + scale);
// 使用计算出来的比例进行缩放
opts.inJustDecodeBounds = false; // 指定加载可以加载出图片.
opts.inSampleSize = scale;
Bitmap bm = BitmapFactory.decodeFile(path, opts);
// 显示到ImageView控件上
ivIcon.setImageBitmap(bm);
}
}