android 放大缩小图片

感谢:http://www.xycoding.com/articles/2014/11/21/android-clipimage/

package com.hrloo.mobile.ui;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Environment;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.commons.support.widget.TitleBar;
import com.hrloo.mobile.R;
import com.hrloo.mobile.base.BaseNoInitDataActivity;
import com.hrloo.mobile.base.ContentView;

import java.io.File;
import java.io.FileOutputStream;

@ContentView(R.layout.activity_crop_handler)
public class CropHandlerActivity extends BaseNoInitDataActivity {

    private View mSelect;
    private ImageView mImg;
    private RelativeLayout mHandlerLayout;
    float downX, downY;
    int state;
    final int ZOOM = 1, DRAG = 0;
    private int top, left;
    float oldSpacing = 1f;
    private TitleBar mTitleBar;

    /**
     * 记录缩放时两指中间点坐标
     */
    private PointF mid = new PointF();
    private boolean isMain, isPointer;
    private int requestCode;

    @Override
    protected void initView() {
        mTitleBar = getTitleBar();
        mSelect = $T(R.id.crop_handler_select);
        mImg = $T(R.id.crop_handler_img);
        mHandlerLayout = $T(R.id.crop_handler_layout);

        mTitleBar.setRightButton("使用", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap bitmap = getBitmap();
                FileOutputStream fos = null;
                String fileName = "cropTemp.jpg";
                try {
                    //判断sd卡是否存在
                    boolean sdCardExist = Environment.getExternalStorageState()
                            .equals(android.os.Environment.MEDIA_MOUNTED);
                    if (sdCardExist) {
                        //获取sdcard的根目录
                        String sdPath = Environment.getExternalStorageDirectory().getPath();

                        //创建程序自己创建的文件夹
                        File tempFile = new File(sdPath + File.separator + fileName);
                        if (!tempFile.exists()) {
                            tempFile.mkdirs();
                        }
                        //创建图片文件
                        File file = new File(sdPath + File.separator + fileName + File.separator + "screen" + ".png");
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        fos = new FileOutputStream(file);
                        if (fos != null) {
                            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
                            fos.close();
                        }
                        Intent intent = new Intent();
                        intent.putExtra("fileName", file.getAbsolutePath());
                        setResult(RESULT_OK, intent);
                        CropHandlerActivity.this.finish();
                    }
                } catch (Exception e) {
                }
            }
        });
        mImg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction() & motionEvent.getActionMasked()) {
                    case MotionEvent.ACTION_POINTER_DOWN:
                        //次要点被点击
                        Log.d("CropHandlerActivity", "ACTION_POINTER_DOWN");
                        oldSpacing = spacing(motionEvent);
                        if (oldSpacing > 10f) {
                            isPointer = false;
                            isMain = false;
                            state = ZOOM;
                            midPoint(mid, motionEvent);
                        }
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        //次要点松开
                        Log.d("CropHandlerActivity", "ACTION_POINTER_UP");
                        isPointer = true;
                        if (isPointer && isMain) {
                            isPointer = false;
                            isMain = false;
                            state = DRAG;
                            oldSpacing = 1f;
                        }
                        break;
                    case MotionEvent.ACTION_DOWN:
                        Log.d("CropHandlerActivity", "ACTION_DOWN");
                        downX = motionEvent.getX();
                        downY = motionEvent.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        Matrix matrix = mImg.getImageMatrix();
                        if (state == DRAG) {
//                        Log.d("CropHandlerActivity", "ACTION_MOVE:" + (motionEvent.getX() - downX) + "  :" + (motionEvent.getY() - downY));
                            matrix.postTranslate(motionEvent.getX() - downX, motionEvent.getY() - downY);
                            downX = motionEvent.getX();
                            downY = motionEvent.getY();
                        } else if (state == ZOOM && !isPointer && !isMain) {
                            float newSpacing = spacing(motionEvent);
                            float scale = newSpacing / oldSpacing;
                            matrix.postScale(scale, scale, mid.x, mid.y);
                            oldSpacing = newSpacing;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        isMain = true;
                        if (isPointer && isMain) {
                            isPointer = false;
                            isMain = false;
                            state = DRAG;
                            oldSpacing = 1f;
                        }
                        break;
                }
                mImg.invalidate();
                return true;
            }
        });
    }

    /**
     * 多点触控时,计算最先放下的两指距离
     *
     * @param event
     * @return
     */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

    /**
     * 多点触控时,计算最先放下的两指中心坐标
     *
     * @param point
     * @param event
     */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }

    public static void startThis(Activity context, String fileUri) {
        Intent intent = new Intent(context, CropHandlerActivity.class);
        intent.putExtra("fileUri", fileUri);
        context.startActivityForResult(intent, 88);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            int layoutWidth = mHandlerLayout.getWidth();
            int layoutHeight = mHandlerLayout.getHeight();
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.splash);
            int imgWidth = bitmap.getWidth();
            int imgHeight = bitmap.getHeight();

            int selectWidth = mSelect.getWidth();
            int selectHeight = mSelect.getHeight();
            float scaleNum;
            if (imgWidth > imgHeight) {
                scaleNum = (selectWidth * 1.0f) / (imgWidth * 1.0f);
                imgHeight = (int) (scaleNum * imgHeight);
                imgWidth = selectWidth;
            } else {
                scaleNum = (selectHeight * 1.0f) / (imgHeight * 1.0f);
                imgWidth = (int) (scaleNum * imgWidth);
                imgHeight = selectHeight;
            }

            Matrix matrix = new Matrix();
            matrix.postScale(scaleNum, scaleNum);

            top = (layoutHeight - selectHeight) / 2;
            left = (layoutWidth - selectWidth) / 2;
            //平移距离
            matrix.postTranslate((layoutWidth - imgWidth) / 2, (layoutHeight - imgHeight) / 2);
            mImg.setScaleType(ImageView.ScaleType.MATRIX);
            mImg.setImageMatrix(matrix);
            mImg.setImageBitmap(bitmap);

        }
    }

    /**
     * 获取裁剪框内截图
     *
     * @return
     */
    private Bitmap getBitmap() {
        // 获取截屏
        mHandlerLayout.setDrawingCacheEnabled(true);
        mHandlerLayout.buildDrawingCache();

        // 获取状态栏高度
        Rect frame = new Rect();
        this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int borderWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
        RelativeLayout.LayoutParams mLayoutParams = (RelativeLayout.LayoutParams) mImg.getLayoutParams();
        Log.d("getBitmap", "mLayoutParams.topMargin:" + mLayoutParams.topMargin + " mLayoutParams.leftMargin:" + mLayoutParams.leftMargin + "   left:" + left + " top:" + top);
        Bitmap finalBitmap = Bitmap.createBitmap(mHandlerLayout.getDrawingCache(),
                left + borderWidth, top + borderWidth, mSelect.getWidth() - 2 * borderWidth,
                mSelect.getHeight() - 2 * borderWidth);

        // 释放资源
        mHandlerLayout.destroyDrawingCache();
        return finalBitmap;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值