添加canvas.translate的限制

时间:2017-04-10 06:34:05

标签: android android-canvas ontouchevent ondraw

我缩放画布,当我移动它时,它会离开画面。

翻译前的屏幕截图(即第一次执行canvas.onDraw()时)

BEFORE TRANSLATE

移动后:

enter image description here

我需要一些条件来说明不要超越这一点(x轴 - 20)。

        canvas.save();
        int maxX, minX;

        minX = /* some condition */;
        maxX = /* some condition */;
        if (mPosX > maxX)
            mPosX = maxX;

        if (mPosX < minX)
            mPosX = minX;

        canvas.translate(mPosX, 0);
        canvas.scale(xScaleFactor, yScaleFactor,
                px / xScaleFactor + left, py / yScaleFactor + canvas.getClipBounds().top);

        paint.setColor(ContextCompat.getColor(getContext(), R.color.green));
        canvas.drawRect(20, 20, width, height, paint);

移动时:

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        mScaleDetector.onTouchEvent(ev);
        int eid = ev.getAction();
        switch (eid & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                px = ev.getX();
                py = ev.getY();

                mLastTouchX = px;
                mActivePointerId = ev.getPointerId(0);
                break;

            case MotionEvent.ACTION_MOVE:
                if (eid == MotionEvent.ACTION_POINTER_UP || eid == MotionEvent.ACTION_POINTER_DOWN) {
                    return false;
                }
                pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK)
                        >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
                final float x = ev.getX(pointerIndex);

                final float dx = x - mLastTouchX;
                mPosX += dx; 
                invalidate();

                mLastTouchX = x;
                break;
                  .......

请帮助获得一些限制矩形远离屏幕的条件。这样就不会创建左侧的空白区域。每次画布无效时,矩形应从x轴的位置20开始。

编辑:

        private Matrix m;
        m = new Matrix();
        m.mapRect(new RectF(20, 0, mPosX, 0));

        // in onDraw()
        canvas.save(); 
        m.setTranslate(mPosX, 0);
        m.setScale(xScaleFactor, yScaleFactor,
                (px + canvas.getClipBounds().left)/ xScaleFactor, (py + canvas.getClipBounds().top)/ yScaleFactor);

        canvas.concat(m);

        paint.setColor(ContextCompat.getColor(getContext(), R.color.green));
        canvas.drawRect(20, 20, width, height, paint);

仍在外出

0 个答案:

没有答案