Android 自定义控件基础-图片预览和多点触控

  今天我记录一下怎么通过自定义控件来实现图片的预览的功能 -- 根据慕课网上学习的内容所写的。
  包含的内容主要有:

  1.图片的多指放大。
  2.图片的双击放大和缩小
  3.图片的滑动。
  4.与ViewPager的冲突解决办法

1.概述

  图片的多指放大,主要用到一个类叫做ScaleGestureDetector,这个类用来一些多指的操作;图片的双击,主要用到一个类叫做GestureDetector,这个类用来处理双击的操作;图片的缩放用到了Matrix类来处理。

2.自定义ImageView,并且完美的加载一张图片

  当我们在使用ImageView时,有时候要处理图片的大小很大或者很小的情况,这时候需要我们手动将图片放大或者缩小。在处理图片的放大和缩小,我们会使用一个类叫做Matrix,这个类来帮我处理图片的缩放和移动。
  有一个问题,就是在处理图片的时候,一定在ImageView加载完了的时候,因为在加载完成之前,控件的大小,我们是不知道的,所以怎么知道ImageView加载完成呢?之后需要我们监听整个视图树,视图树一旦有更新,我们便知道ImageView加载完成了。
  设置监听事件和取消监听事件分别在两个方法里面:onAttachedToWindow和onDetachedFromWindow。这两个方法分别表示该控件加载到窗口和该控件从窗口上移除时。

@Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }

    @Override
    public void onGlobalLayout() {
        if (!mOnce) {
            //获得控件的宽和高
            int width = getWidth();
            int height = getHeight();
            Log.i("main", "width = " + width + " height = " + height);
            //获得图片的宽和高
            Drawable d = getDrawable();
            if (d == null) {
                return;
            }
            int dh = d.getIntrinsicHeight();
            int dw = d.getIntrinsicWidth();
            Log.i("main", "dw = " + dw + " dh = " + dh);
            float scale = 1;
            if (dw > width && dh < height) {
                scale = width * 1.0f / dw;
            }
            if (dw < width && dh > height) {
                scale = height * 1.0f / dh;
            }
            if ((dh > height && dw > width) || (dh < height && dw < width)) {
                scale = Math.min(height * 1.0f / dh, width * 1.0f / dw);
            }
            int dx = (int) (width / 2 - dw/ 2);
            int dy = (int) (height / 2 - dh / 2);
            mInitScale = scale;
            mMaxScale = 4 * scale;
            mMinScale = 0.7f * scale;
            mMidScale = 2 * scale;
            mMatrix.postTranslate(dx, dy);
            mMatrix.postScale(scale, scale, width / 2, height / 2);
            setImageMatrix(mMatrix);
            RectF rectF = getRectF();
            Log.i("main", "width = " + rectF.width() + " height = " + rectF.height());
            mOnce = true;
        }
    }

3.多指放大和缩小

  多指的操作用到了一个类--ScaleGestureDetector。我们得定义ScaleGestureDetector类型的变量,并且在构造方法里面初始化它。初始化的时候需要我们实现OnScaleGestureListener,并且实现三个方法

public boolean onScale(ScaleGestureDetector detector); // 多指缩放时调用
public boolean onScaleBegin(ScaleGestureDetector detector); //开始缩放时调用
public void onScaleEnd(ScaleGestureDetector detector);  //缩放结束时调用

  要想这三个方法接受到我们的手指事件,我们还必须在onTouch方法这样写:mScaleGestureDetector.onTouchEvent(event);将事件传到ScaleGestureDetector里面去。

@Override
    public boolean onScale(ScaleGestureDetector detector) {
        if (getDrawable() == null) {
            return true;
        }
        float scaleFactor = detector.getScaleFactor();
        mMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
        setImageMatrix(mMatrix);
        checkBorderAndCenterWhenScale();
        return true;
    }

    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
        float scale = getScale();
        if (scale > mMaxScale) {
            mMatrix.postScale(mMaxScale / scale, mMaxScale / scale, detector.getFocusX(), detector.getFocusY());
        }
        if (scale < mMinScale) {
            mMatrix.postScale(mMinScale / scale, mMinScale / scale, detector.getFocusX(), detector.getFocusY());
        }
        setImageMatrix(mMatrix);
        checkBorderAndCenterWhenScale();
    }
private float getScale() {
         float[] values = new float[9];
         mMatrix.getValues(values);
         return values[Matrix.MSCALE_X];
}

  在我们根据手指聚集的焦点缩放,会发现图片会到处乱跑。这时候还需要加入一个边界限定的函数。

private void checkBorderAndCenterWhenScale() {
        //获得控件的宽和高
        int width = getWidth();
        int height = getHeight();
        //获得图片的宽和高
        Drawable d = getDrawable();
        if (d == null) {
            return;
        }
        int dh = d.getIntrinsicHeight();
        int dw = d.getIntrinsicWidth();
        float dx = 0;
        float dy = 0;
        RectF rectF = getRectF();
        //放大的调整
        //左右
        if (rectF.width() >= width) {
            //图片向右偏移了,需要向左调整
            if (rectF.left > 0) {
                dx = -rectF.left;
            }
            //图片向左偏移了,需要向右调整了
            if (rectF.right < width) {
                dx = width - rectF.right;
            }
        }
        if (rectF.height() >= height) {
            //图片向下偏移了,需要向上调整
            if (rectF.top > 0) {
                dy = -rectF.top;
            }
            //图片向上偏移了,需要向下调整
            if (rectF.bottom < height) {
                dy = height - rectF.bottom;
            }
        }
        //缩小的调整
        //左右
        if (rectF.width() <= width) {
            /**
             *
             *dx = width / 2 - (rectF.left + rectF.right) / 2
             *
             */
            dx = width / 2 - (rectF.left + rectF.right) / 2;
        }
        if (rectF.height() <= height) {
            /**
             * dy = height / 2 - (rectF.top + rectF.bottom) / 2
             */
            dy = height / 2 - (rectF.top + rectF.bottom) / 2;
        }
        mMatrix.postTranslate(dx, dy);
        setImageMatrix(mMatrix);
    }

4.双击放大和缩小

  双击放大和缩小需要一个类:GestureDetector。这个类里面含有一些双击事件处理的方法。
  我们在初始化GestureDetector变量的时候,需要我们传入一个OnGestureListener接口类型的参数,我们传入SimpleOnGestureListener就行,因为这个类对很多方法进行了空实现,不能我们去写很多的代码。

mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onDoubleTap(MotionEvent e) {
                int x = (int) e.getX();
                int y = (int) e.getY();
                float scale = getScale();
                AutoScaleRunnable autoScaleRunnable = null;
                if(scale < mInitScale)
                {
                    //mMatrix.postScale(mInitScale / scale, mInitScale / scale, x, y);
                    autoScaleRunnable = new AutoScaleRunnable(x, y, mInitScale);
                }
                if(scale >= mInitScale && scale < mMidScale)
                {
                    //mMatrix.postScale(mMidScale / scale, mMidScale / scale ,x, y);
                    autoScaleRunnable = new AutoScaleRunnable(x, y, mMidScale);
                }
                if(scale >= mMidScale && scale < mMaxScale)
                {
                    //mMatrix.postScale(mMaxScale / scale, mMaxScale / scale, x, y);
                    autoScaleRunnable = new AutoScaleRunnable(x, y, mMaxScale);
                }
                if(scale == mMaxScale)
                {
                   // mMatrix.postScale(mInitScale / scale, mInitScale /  scale, x, y);
                    autoScaleRunnable = new AutoScaleRunnable(x, y, mInitScale);
                }
                //setImageMatrix(mMatrix);
                postDelayed(autoScaleRunnable, 16);
                return true;
            }
        });

  同时,我们还是在onTouch里面将事件传过来。

if(mGestureDetector.onTouchEvent(event))
{
    return true;
}

  双击放大或者缩小,我们会发现,放大和缩小都是瞬间完成,所以我们需要实现缓慢的完成,这个需要我们调用postDelayed方法。postDelayed需要我们传入一个Runnabl,所以我们得自定义一个Runnable。

rivate class AutoScaleRunnable implements Runnable
    {
        private int x = 0;
        private int y = 0;
        private float mTargetScale = 0;
        private float mTempScale = 0;
        private static final float BIGGER = 1.13f;
        private static final float SMALLER = 0.87f;
        public AutoScaleRunnable(int x, int y, float targetScale)
        {
            this.x = x;
            this.y = y;
            this.mTargetScale = targetScale;
            float scale = getScale();
            if(scale > targetScale)
            {
                mTempScale = SMALLER;
            }
            if(scale < targetScale)
            {
                mTempScale = BIGGER;
            }
        }
        @Override
        public void run() {
            mMatrix.postScale(mTempScale, mTempScale, x, y);
            setImageMatrix(mMatrix);

            float currentScale = getScale();
            if((mTempScale > 1.0f && currentScale < mTargetScale)||(mTempScale < 1.0f && currentScale > mTargetScale))
            {
                postDelayed(this, 16);
            }
            else
            {
                float scale = mTargetScale / getScale();
                mMatrix.postScale(scale, scale, x, y);
                setImageMatrix(mMatrix);
                checkBorderAndCenterWhenScale();
            }

        }
    }

5.图片的移动

float x = 0;
        float y = 0;
        int pointCount = event.getPointerCount();
        for (int i = 0; i < pointCount; i++) {
            x += event.getX(i);
            y += event.getY(i);
        }
        //Log.i("main", "pointCount = " + pointCount);
        x /= pointCount * 1.0f;
        y /= pointCount * 1.0f;
        if (pointCount != mLastPointCount) {
            mIsCanDrag = false;
            mLastX = x;
            mLastY = y;
        }
        mLastPointCount = pointCount;
        RectF rectF = getRectF();
        Log.i("main", "rectFHeight = " + rectF.height() + " rectFWidth = " + rectF.width() + "\n width = " + getWidth() + " height = " + getHeight());
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                if(rectF.width() > getWidth() || rectF.height() > getHeight())
                {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                if(rectF.width() > getWidth() || rectF.height() >getHeight())
                {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                mIsCheckTopAndBottom = mIsCheckLeftAndRight = true;
                float dx = x - mLastX;
                float dy = y - mLastY;
                if (!mIsCanDrag) {
                    mIsCanDrag = isMoveAction(dx, dy);
                }
                if (mIsCanDrag) {
                    if (rectF.height() <= getHeight()) {
                        mIsCheckTopAndBottom = false;
                        dy = 0;
                    }
                    if (rectF.width() <= getWidth()) {
                        mIsCheckLeftAndRight = false;
                        dx = 0;
                    }
                    mMatrix.postTranslate(dx * 1.2f, dy * 1.2f);
                    setImageMatrix(mMatrix);
                    checkBorderWhenTranslate();
                }
                mLastX = x;
                mLastY = y;
                break;
            }
            case MotionEvent.ACTION_UP: {
                mLastPointCount = 0;
                break;
            }
        }

  在移动的时候,也需要我们进行边界的限定

private void checkBorderWhenTranslate()
    {
        RectF rectF = getRectF();
        int deltaX = 0;
        int deltaY = 0;
        int height = getHeight();
        int width = getWidth();
        if(rectF.left > 0 && mIsCheckLeftAndRight) {
            deltaX = (int) -rectF.left;
        }
        if(rectF.right < width && mIsCheckLeftAndRight)
        {
            deltaX = (int) (width - rectF.right);
        }
        if(rectF.top > 0 && mIsCheckTopAndBottom)
        {
            deltaY = (int) - rectF.top;
        }
        if(rectF.bottom < height && mIsCheckTopAndBottom)
        {
            deltaY = (int) (height - rectF.bottom);
        }
        mMatrix.postTranslate(deltaX, deltaY);
        setImageMatrix(mMatrix);
    }

5.冲突事件的处理

  当我们在移动图片的时候,我们会发现ViewPager会截获子View的事件。这时候我们只需要在我们想要不被截获的时候调用此方法就行:getParent().requestDisallowInterceptTouchEvent(true);

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容