【Android日常--- ImageView的手势缩放-图片初始化缩放-自定义ScaleType】

问题与结论:

  1. 怎样进行手势缩放
    • 采用 Matrix 对图片进行缩放,调用ImageView.setImageMatrix 设置
    • 采用 ScaleGestureDetector 获取Touch事件对应的scale数值
  2. 怎样限定ImageVeiw的初始缩放规则 (自定义ScaleType)
    • 如:图片宽度 scale 到屏幕宽度,高度 按图片比例缩放。 (最大程度展示图片)
    • 在onMeasure中对imageScale 进行初始化

注意

  1. ImageView的ScaleType要设置为 matrix
setScaleType(ImageView.ScaleType.MATRIX);

代码

1. 手势缩放

手势缩放代码
TouchScaleImageView
项目代码,防止类被重构移动

public class TouchScaleImageView extends android.support.v7.widget.AppCompatImageView {

    protected Matrix mImgMatrix;

    // We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // Remember some things for zooming
    PointF last = new PointF();
    PointF start = new PointF();
    float minScale = 1f;
    float maxScale = 3f;
    float[] m;


    int viewWidth, viewHeight;
    protected float saveScale = 1f;
    protected float origWidth, origHeight;
    int oldMeasuredWidth, oldMeasuredHeight;
    private int mTouchSlop;
    protected boolean mTouchable = true;
    ScaleGestureDetector mScaleDetector;
    private OnScaleCallback mScaleCallback;
    Context context;

    public TouchScaleImageView(Context context) {
        super(context);
        sharedConstructing(context);
    }

    public TouchScaleImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        sharedConstructing(context);
    }

    public TouchScaleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        sharedConstructing(context);
    }

    public interface OnScaleCallback {
        void onScale();
        void onScaleEnd();
    }

    public void setScaleCallback(OnScaleCallback callback) {
        mScaleCallback = callback;
    }

    public void setTouchable(boolean touchable) {
        mTouchable = touchable;
    }

    private void sharedConstructing(Context context) {
        super.setClickable(true);
        this.context = context;
        ViewConfiguration vc = ViewConfiguration.get(context);
        mTouchSlop = vc.getScaledTouchSlop();
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        mImgMatrix = new Matrix();
        m = new float[9];
        setImageMatrix(mImgMatrix);
        setScaleType(ImageView.ScaleType.MATRIX);

        setOnTouchListener((v, event) -> {
            if (!mTouchable) {
                return false;
            }
            mScaleDetector.onTouchEvent(event);
            PointF curr = new PointF(event.getX(), event.getY());

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    last.set(curr);
                    start.set(last);
                    mode = DRAG;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        float deltaX = curr.x - last.x;
                        float deltaY = curr.y - last.y;
                        float fixTransX = getFixDragTrans(deltaX, viewWidth, origWidth * saveScale);
                        float fixTransY = getFixDragTrans(deltaY, viewHeight, origHeight * saveScale);
                        mImgMatrix.postTranslate(fixTransX, fixTransY);
                        fixTrans();
                        last.set(curr.x, curr.y);
                    }
                    break;

                case MotionEvent.ACTION_UP:
                    mode = NONE;
                    int xDiff = (int) Math.abs(curr.x - start.x);
                    int yDiff = (int) Math.abs(curr.y - start.y);
                    if (xDiff < mTouchSlop && yDiff < mTouchSlop)
                        if (!executeClickAction(curr.x, curr.y)) {
                            performClick();
                        }
                    break;

                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
            }

            setImageMatrix(mImgMatrix);
            invalidate();
            return true; // indicate event was handled
        });
    }

    protected boolean executeClickAction(float x, float y) {
        return false;
    }

    public void setMaxZoom(float x) {
        maxScale = x;
    }

    public boolean isScaled() {
        return saveScale != 1;
    }

    public void resetStatus() {
        saveScale = 1;
    }

    protected void onTouchScaling() {
        if (mScaleCallback != null) {
            mScaleCallback.onScale();
        }
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            mode = ZOOM;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            float mScaleFactor = detector.getScaleFactor();
            float origScale = saveScale;
            saveScale *= mScaleFactor;
            if (saveScale > maxScale) {
                saveScale = maxScale;
                mScaleFactor = maxScale / origScale;
            } else if (saveScale < minScale) {
                saveScale = minScale;
                mScaleFactor = minScale / origScale;
            }

            if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight)
                mImgMatrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2, viewHeight / 2);
            else
                mImgMatrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());

            fixTrans();
            onTouchScaling();
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            super.onScaleEnd(detector);

            if (mScaleCallback != null) {
                mScaleCallback.onScaleEnd();
            }
        }
    }

    void fixTrans() {
        mImgMatrix.getValues(m);
        float transX = m[Matrix.MTRANS_X];
        float transY = m[Matrix.MTRANS_Y];

        float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
        float fixTransY = getFixTrans(transY, viewHeight, origHeight * saveScale);

        if (fixTransX != 0 || fixTransY != 0)
            mImgMatrix.postTranslate(fixTransX, fixTransY);
    }

    float getFixTrans(float trans, float viewSize, float contentSize) {
        float minTrans, maxTrans;

        if (contentSize <= viewSize) {
            minTrans = 0;
            maxTrans = viewSize - contentSize;
        } else {
            minTrans = viewSize - contentSize;
            maxTrans = 0;
        }

        if (trans < minTrans)
            return -trans + minTrans;
        if (trans > maxTrans)
            return -trans + maxTrans;
        return 0;
    }

    float getFixDragTrans(float delta, float viewSize, float contentSize) {
        if (contentSize <= viewSize) {
            return 0;
        }
        return delta;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        viewWidth = View.MeasureSpec.getSize(widthMeasureSpec);
        viewHeight = View.MeasureSpec.getSize(heightMeasureSpec);

        //
        // Rescales image on rotation
        //
        if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight
                || viewWidth == 0 || viewHeight == 0)
            return;
        oldMeasuredHeight = viewHeight;
        oldMeasuredWidth = viewWidth;

        if (saveScale == 1) {
            //Fit to screen.
            float scale;

            Drawable drawable = getDrawable();
            if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0)
                return;
            doInitScale(drawable);
        }
        fixTrans();
    }

    /**
     * 设置Image初始化时的效果
     * @param drawable
     */
    protected void doInitScale(Drawable drawable) {
        float scale;
        int bmWidth = drawable.getIntrinsicWidth();
        int bmHeight = drawable.getIntrinsicHeight();
        float scaleX = (float) viewWidth / (float) bmWidth;
        float scaleY = (float) viewHeight / (float) bmHeight;
        scale = Math.min(scaleX, scaleY);
        mImgMatrix.setScale(scale, scale);

        // Center the image
        float redundantYSpace = (float) viewHeight - (scale * (float) bmHeight);
        float redundantXSpace = (float) viewWidth - (scale * (float) bmWidth);
        redundantYSpace /= (float) 2;
        redundantXSpace /= (float) 2;

        mImgMatrix.postTranslate(redundantXSpace, redundantYSpace);

        origWidth = viewWidth - 2 * redundantXSpace;
        origHeight = viewHeight - 2 * redundantYSpace;
        setImageMatrix(mImgMatrix);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        if (mNeedBlackBg) {
            canvas.drawColor(Color.BLACK);
        }
        super.onDraw(canvas);
    }

    private boolean mNeedBlackBg = false;

    public void needBlackBg(boolean isNeed) {
        mNeedBlackBg = isNeed;
    }
}
2. 怎样限定ImageVeiw的初始缩放规则 (自定义ScaleType)

继承TouchScaleImageView,重写doInitScale(在父类被onMeasure调用)

public class FitWidthScaleImageView extends TouchScaleImageView {

    public FitWidthScaleImageView(Context context) {
        super(context);
    }

    public FitWidthScaleImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FitWidthScaleImageView(Context context,  AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void doInitScale(Drawable drawable) {
        float scale = 1.0f;
        int bmWidth = drawable.getIntrinsicWidth();
        int bmHeight = drawable.getIntrinsicHeight();
        float scaleX = (float) viewWidth / (float) bmWidth;
        float scaleY = (float) viewHeight / (float) bmHeight;

        scale = scaleX;
        mImgMatrix.setScale(scale, scale);

        if (scaleY >= scaleX) {
            // picture y small than x. scale x, cause y beyond screen.
            // so picture from begin not center layout.
            float redundantYSpace = (viewHeight - (bmHeight * scale)) * 0.5f;
            mImgMatrix.postTranslate(0, redundantYSpace);
        }

        origWidth = scale * bmWidth;
        origHeight = scale * bmHeight;
        setImageMatrix(mImgMatrix);
    }

}

代码片段

获取图片尺寸
        int bmWidth = drawable.getIntrinsicWidth();
        int bmHeight = drawable.getIntrinsicHeight();
1. 图片居中
        // Center the image
        float redundantYSpace = (float) viewHeight - (scale * (float) bmHeight);
        float redundantXSpace = (float) viewWidth - (scale * (float) bmWidth);
        redundantYSpace /= (float) 2;
        redundantXSpace /= (float) 2;

        mImgMatrix.postTranslate(redundantXSpace, redundantYSpace);
2. 填满宽度,高度按图片比例scale
        float scale = 1.0f;
        int bmWidth = drawable.getIntrinsicWidth();
        float scaleX = (float) viewWidth / (float) bmWidth;
        scale = scaleX;
        mImgMatrix.setScale(scale, scale);
        setImageMatrix(mImgMatrix);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值