Android 点击图片放大

640?wx_fmt=gif

640?wx_fmt=jpeg

Linux编程 点击右侧关注,免费入门到精通! 640?wx_fmt=jpeg


作者丨猎羽 

https://blog.csdn.net/feather_wch/article/details/5204


这里是加载的网络图片(url),点击图片后,将url作为参数打开Activity


使用方法


   private static final int BINARYSEARCH_THRESHOLD   = Intent intent = new Intent();
intent.setClass(QuestionSingleChoiceActivity.this, PicturePreviewActivity.class);
intent.putExtra("url", url);
startActivity(intent);


Activity代码(复制使用即可)


 /**
 * 大图预览 功能描述:一般我们浏览一个应用,别人发布的状态或新闻都会有很多配图, 我们点击图片时可以浏览大图,这张大图一般可以放大,放大到超过屏幕后
 * 可以移动 需要从activity的Intent传参数过来 传入参数:url 大图下载地址 smallPath 缩略图存在本地的地址
 *
 * @author Administrator
 */

public class PicturePreviewActivity extends Activity {
    private ZoomImageView zoomView;
    private Context ctx;
    private GestureDetector gestureDetector;
    private LinearLayout layout;
    private boolean isFile;
    private String TAG = PicturePreviewActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //不显示系统的标题栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_picture_preview);
        ctx = this;
        zoomView = (ZoomImageView) findViewById(R.id.zoom_view);
        zoomView.getActivity(PicturePreviewActivity.this);
        layout = (LinearLayout) this.findViewById(R.id.layout_picture_preview);
        /* 大图的下载地址 */
        final String url = getIntent().getStringExtra("url");

        if (url.startsWith("http:")) {//是网络地址
            this.isFile = false;
        } else {
            this.isFile = true;
        }

        /* 缩略图存储在本地的地址 */
        final String smallPath = getIntent().getStringExtra("smallPath");
        final int identify = getIntent().getIntExtra("indentify", -1);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        final int widthPixels = metrics.widthPixels;
        final int heightPixels = metrics.heightPixels;
        File bigPicFile = new File(getLocalPath(url));

        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "背景被点击");
                PicturePreviewActivity.this.finish();
            }
        });

        if (isFile) {
            zoomView.setImageBitmap(zoomBitmap(
                    BitmapFactory.decodeFile(url), widthPixels,
                    heightPixels));
        } else {

            if (bigPicFile.exists()) {/* 如果已经下载过了,直接从本地文件中读取 */
                zoomView.setImageBitmap(zoomBitmap(
                        BitmapFactory.decodeFile(getLocalPath(url)), widthPixels,
                        heightPixels));
            } else if (!TextUtils.isEmpty(url)) {
                ProgressDialogHandle handle = new ProgressDialogHandle(this) {
                    Bitmap bitmap = null;

                    @Override
                    public void handleData() throws
                            Exception 
{

                        if (!isFile)  //从网络读取
                            bitmap = getBitMapFromUrl(url);


                        if (bitmap != null) {
                            savePhotoToSDCard(
                                    zoomBitmap(bitmap, widthPixels, heightPixels),
                                    getLocalPath(url));
                        }
                    }

                    @Override
                    public String initialContent() {
                        return null;
                    }

                    @Override
                    public void updateUI() {
                        if (bitmap != null) {
                            // recycle();

                            zoomView.setImageBitmap(zoomBitmap(bitmap, widthPixels,
                                    heightPixels));
                        } else {
                            Toast.makeText(ctx, "图片预览图下载失败",
                                    Toast.LENGTH_LONG).show();
                            PicturePreviewActivity.this.finish();
                        }
                    }

                };
                if (TextUtils.isEmpty(smallPath) && identify != -1) {
                    handle.setBackground(BitmapFactory.decodeResource(
                            getResources(), identify));
                } else {
                    handle.setBackground(BitmapFactory.decodeFile(smallPath));
                }
                handle.show();
            }
        }
        gestureDetector = new GestureDetector(this,
                new GestureDetector.SimpleOnGestureListener() {
                    @Override
                    public boolean onFling(MotionEvent e1, MotionEvent e2,
                                           float velocityX, float velocityY)
 
{
                        float x = e2.getX() - e1.getX();
                        if (x > 0) {
                            prePicture();
                        } else if (x < 0) {

                            nextPicture();
                        }
                        return true;
                    }
                });
    }

    protected void nextPicture() {
        // TODO Auto-generated method stub

    }

    protected void prePicture() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onResume() {
        super.onResume();
        // recycle();
    }

    public void recycle() {
        if (zoomView != null && zoomView.getDrawable() != null) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) zoomView
                    .getDrawable();
            if (bitmapDrawable != null && bitmapDrawable.getBitmap() != null
                    && !bitmapDrawable.getBitmap().isRecycled())

            {
                bitmapDrawable.getBitmap().recycle();
            }
        }
    }


    public Bitmap getBitMapFromUrl(String url) {
        Bitmap bitmap = null;
        URL u = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        try {
            u = new URL(url);
            conn = (HttpURLConnection) u.openConnection();
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            conn.disconnect();
        }
        return bitmap;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    /**
     * Resize the bitmap
     *
     * @param bitmap
     * @param width
     * @param height
     * @return
     */

    public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
        if (bitmap == null)
            return bitmap;
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        if (scaleWidth < scaleHeight) {
            matrix.postScale(scaleWidth, scaleWidth);
        } else {
            matrix.postScale(scaleHeight, scaleHeight);
        }
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 00, w, h, matrix, true);
        return newbmp;
    }

    public static String getLocalPath(String url) {
        String fileName = "temp.png";
        if (url != null) {
            if (url.contains("/")) {
                fileName = url
                        .substring(url.lastIndexOf("/") + 1, url.length());
            }
            if (fileName != null && fileName.contains("&")) {
                fileName = fileName.replaceAll("&""");
            }
            if (fileName != null && fileName.contains("%")) {
                fileName = fileName.replaceAll("%""");
            }
        }
        return Environment.getExternalStorageDirectory() + "/weike/PracticeImage/" + fileName;
    }


    public static void savePhotoToSDCard(Bitmap photoBitmap, String fullPath) {
        if (checkSDCardAvailable()) {
            File file = new File(fullPath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            File photoFile = new File(fullPath);
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(photoFile);
                if (photoBitmap != null) {
                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,
                            fileOutputStream)) {
                        fileOutputStream.flush();
                    }
                }
            } catch (FileNotFoundException e) {
                photoFile.delete();
                e.printStackTrace();
            } catch (IOException e) {
                photoFile.delete();
                e.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    // if (photoBitmap != null && !photoBitmap.isRecycled()) {
                    // photoBitmap.recycle();
                    // }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static boolean checkSDCardAvailable() {
        return android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
    }


    public void closeActivity() {
        this.finish();
    }

}


 推荐↓↓↓ 

640?wx_fmt=png

?16个技术公众号】都在这里!

涵盖:程序员大咖、源码共读、程序员共读、数据结构与算法、黑客技术和网络安全、大数据科技、编程前端、Java、Python、Web编程开发、Android、iOS开发、Linux、数据库研发、幽默程序员等。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值