Android-加载大图片

来源:互联网 发布:读书看报软件 编辑:程序博客网 时间:2024/05/17 06:37

manifest权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
布局文件:
<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:gravity="center_horizontal"    tools:context=".MainActivity">    <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="onclick"        android:text="加载图片" />    <ImageView        android:id="@+id/image"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></RelativeLayout>

效果如图:



MainActivity.java
package com.example.yulongji.android8;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Environment;import android.view.Display;import android.view.View;import android.widget.ImageView;public class MainActivity extends Activity {    ImageView image;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        image = (ImageView) findViewById(R.id.image);    }    public void onclick(View view) {        //解析图片时需要使用到的参数都封装在这个对象里了        BitmapFactory.Options opt = new BitmapFactory.Options();        //不为像素申请内存,只获取图片宽高        opt.inJustDecodeBounds = true;        //图片的路径        String path = Environment.getExternalStorageDirectory() + "/" + "1.png";        BitmapFactory.decodeFile(path, opt);        //拿到图片宽高        int imageWidth = opt.outWidth;        int imageHeight = opt.outHeight;        System.out.println("图片高度:" + imageHeight + "; 图片宽度:" + imageWidth);        Display dp = getWindowManager().getDefaultDisplay();        //拿到屏幕宽高        int screenWidth = dp.getWidth();        int screenHeight = dp.getHeight();        System.out.println("getRotation()" + dp.getRotation() + ":" + "getFlags()" + dp.getFlags());        System.out.println("屏幕高度:" + screenHeight + "; 屏幕宽度:" + screenWidth);        //计算缩放比例        int scale = 1;        int scaleWidth = imageWidth / screenWidth;        int scaleHeight = imageHeight / screenHeight;        System.out.println("缩放高度:" + scaleHeight + ";缩放宽度:" + scaleWidth);        if (scaleWidth >= scaleHeight && scaleWidth >= 1) {            scale = scaleWidth;        } else if (scaleWidth <= imageHeight && scaleWidth >= 1) {            scale = scaleHeight;        }        System.out.println("缩放比例:" + scale);        //设置缩放比例        opt.inSampleSize = scale;        opt.inJustDecodeBounds = false;        Bitmap bm = BitmapFactory.decodeFile(path, opt);        //将操作后的图片放入imageview中        image.setImageBitmap(bm);    }}

















0 0