<LinearLayout 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:orientation="vertical" tools:context="hhh.exercise.smultimedia_a_image.MainActivity" > <EditText android:id="@+id/ed" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="a.jpg" android:textColor="#00ff00" android:textSize="30sp" /> <requestFocus /> <Button android:onClick="see" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="点击看片" android:textColor="#00ffff" android:textSize="30sp" /> <ImageView android:id="@+id/iv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:src="@drawable/ic_launcher" /> </LinearLayout>
public class MainActivity extends Activity {
private EditText ed;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed = (EditText) findViewById(R.id.ed);
iv = (ImageView) findViewById(R.id.iv);
}
public void see(View view) {
// 确定要加载的图片(这里为了调试方面,把所有的图片都放在SD卡中,然后在界面上输入图片的名字,根据给名字拼接字符串)
String fileName = ed.getText().toString();
String path = Environment.getExternalStorageDirectory().getPath()+ "/" + fileName;
// 该类为位图工厂(BitmapFactory)的内部类,用来封装参数对象
Options opts = new Options();
// 不为像素申请内存,只获取图片的宽、高信息
// inJustDecodeBound该字段设置为true,那么位图工厂构建BitMap对象时返回的是空值,但是会把图片的一些信息返回在Options对象中(如图片的宽、高等)
opts.inJustDecodeBounds = true;
// 第二个参数是解析图片时传入的参数,由于可能传入的参数过多,所以直接把所有参数封装成一个对象
BitmapFactory.decodeFile(path, opts);
// 获取图片的额宽高
int imgWidth = opts.outWidth;
int imgHeight = opts.outHeight;
// 获取当前手机屏幕的宽高
Display dp = getWindowManager().getDefaultDisplay();
int screenWidth = dp.getWidth();
int screenHeight = dp.getHeight();
// 设置默认缩放比为1
int scale = 1;
// 计算图片宽高与屏幕宽高比例,即计算宽缩放比,高缩放比
int scaleWidth = imgWidth / screenWidth;
int scaleHeight = imgHeight / screenHeight;
// 选择缩放比例,如果图片比屏幕小,就不进行缩放.如果图片比屏幕大,但是宽高缩放比例不同,选择缩放比大
if (scaleWidth >= scaleHeight && scaleWidth > 1) {
scale = scaleWidth;
} else if (scaleWidth < scaleHeight && scaleHeight > 1) {
scale = scaleHeight;
}
// 在Options的对象中设置缩放比例
opts.inSampleSize = scale;
// 一定要把inJustDecodeBound该字段设置为false,实际上默认值是false,
// 但是在前面的代码中已经改为了true,所以要更改过来。当然,也可以重新new 一个Option是对象
opts.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeFile(path, opts);
iv.setImageBitmap(bm);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有