खींचें और स्केल करें

'लिखें' सुविधा आज़माएं
Android के लिए, Jetpack Compose को यूज़र इंटरफ़ेस (यूआई) टूलकिट के तौर पर सुझाया जाता है. Compose में टच और इनपुट इस्तेमाल करने का तरीका जानें.

इस दस्तावेज़ में, स्क्रीन पर मौजूद ऑब्जेक्ट को खींचने और उनके साइज़ में बदलाव करने के लिए, टच जेस्चर का इस्तेमाल करने का तरीका बताया गया है. इसके लिए, टच इवेंट को इंटरसेप्ट करने के लिए onTouchEvent() का इस्तेमाल किया जाता है.

किसी ऑब्जेक्ट को खींचना और छोड़ना

टच जेस्चर का इस्तेमाल, स्क्रीन पर किसी ऑब्जेक्ट को खींचने के लिए किया जाता है.

खींचकर छोड़ने या स्क्रोल करने की कार्रवाई में, ऐप्लिकेशन को मूल पॉइंटर पर नज़र बनाए रखनी होती है. भले ही, स्क्रीन पर अन्य उंगलियां भी छू रही हों. उदाहरण के लिए, मान लें कि इमेज को खींचते समय, उपयोगकर्ता ने टच स्क्रीन पर दूसरी उंगली रखी और पहली उंगली हटा दी. अगर आपका ऐप्लिकेशन सिर्फ़ अलग-अलग पॉइंटर को ट्रैक कर रहा है, तो वह दूसरे पॉइंटर को डिफ़ॉल्ट के तौर पर मानता है और इमेज को उस जगह पर ले जाता है.

ऐसा होने से रोकने के लिए, आपके ऐप्लिकेशन को ओरिजनल पॉइंटर और उसके बाद के पॉइंटर के बीच अंतर करना होगा. ऐसा करने के लिए, यह मल्टी-टच जेस्चर मैनेज करें में बताए गए तरीके से, ACTION_POINTER_DOWN और ACTION_POINTER_UP इवेंट को ट्रैक करता है. जब भी सेकंडरी पॉइंटर नीचे या ऊपर जाता है, तो ACTION_POINTER_DOWN और ACTION_POINTER_UP को onTouchEvent() कॉलबैक में पास किया जाता है.

ACTION_POINTER_UP मामले में, इस इंडेक्स को निकाला जा सकता है और यह पक्का किया जा सकता है कि ऐक्टिव पॉइंटर आईडी, ऐसे पॉइंटर का रेफ़रंस न दे रहा हो जो अब स्क्रीन को छू नहीं रहा है. अगर ऐसा है, तो किसी दूसरे पॉइंटर को चालू करने के लिए चुना जा सकता है और उसकी मौजूदा X और Y पोज़िशन सेव की जा सकती है. स्क्रीन पर मौजूद ऑब्जेक्ट को एक जगह से दूसरी जगह ले जाने के लिए, ACTION_MOVE के मामले में सेव की गई इस पोज़िशन का इस्तेमाल करके दूरी का हिसाब लगाएं. इस तरह, ऐप्लिकेशन हमेशा सही पॉइंटर के डेटा का इस्तेमाल करके, चलने की दूरी का हिसाब लगाता है.

इस कोड स्निपेट की मदद से, उपयोगकर्ता किसी ऑब्जेक्ट को स्क्रीन पर खींचकर छोड़ सकता है. यह ऐक्टिव पॉइंटर की शुरुआती पोज़िशन रिकॉर्ड करता है, पॉइंटर की तय की गई दूरी का हिसाब लगाता है, और ऑब्जेक्ट को नई पोज़िशन पर ले जाता है. यह अतिरिक्त पॉइंटर की संभावना को भी सही तरीके से मैनेज करता है.

स्निपेट में getActionMasked() वाला तरीका इस्तेमाल किया गया है. किसी MotionEvent की कार्रवाई को वापस पाने के लिए, हमेशा इस तरीके का इस्तेमाल करें.

Kotlin

// The "active pointer" is the one moving the object.
private var mActivePointerId = INVALID_POINTER_ID

override fun onTouchEvent(ev: MotionEvent): Boolean {
    // Let the ScaleGestureDetector inspect all events.
    mScaleDetector.onTouchEvent(ev)

    val action = MotionEventCompat.getActionMasked(ev)

    when (action) {
        MotionEvent.ACTION_DOWN -> {
            MotionEventCompat.getActionIndex(ev).also { pointerIndex ->
                // Remember where you start for dragging.
                mLastTouchX = MotionEventCompat.getX(ev, pointerIndex)
                mLastTouchY = MotionEventCompat.getY(ev, pointerIndex)
            }

            // Save the ID of this pointer for dragging.
            mActivePointerId = MotionEventCompat.getPointerId(ev, 0)
        }

        MotionEvent.ACTION_MOVE -> {
            // Find the index of the active pointer and fetch its position.
            val (x: Float, y: Float) =
                    MotionEventCompat.findPointerIndex(ev, mActivePointerId).let { pointerIndex ->
                        // Calculate the distance moved.
                        MotionEventCompat.getX(ev, pointerIndex) to
                                MotionEventCompat.getY(ev, pointerIndex)
                    }

            mPosX += x - mLastTouchX
            mPosY += y - mLastTouchY

            invalidate()

            // Remember this touch position for the next move event.
            mLastTouchX = x
            mLastTouchY = y
        }
        MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
            mActivePointerId = INVALID_POINTER_ID
        }
        MotionEvent.ACTION_POINTER_UP -> {

            MotionEventCompat.getActionIndex(ev).also { pointerIndex ->
                MotionEventCompat.getPointerId(ev, pointerIndex)
                        .takeIf { it == mActivePointerId }
                        ?.run {
                            // This is the active pointer going up. Choose a new
                            // active pointer and adjust it accordingly.
                            val newPointerIndex = if (pointerIndex == 0) 1 else 0
                            mLastTouchX = MotionEventCompat.getX(ev, newPointerIndex)
                            mLastTouchY = MotionEventCompat.getY(ev, newPointerIndex)
                            mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex)
                        }
            }
        }
    }
    return true
}

Java

// The "active pointer" is the one moving the object.
private int mActivePointerId = INVALID_POINTER_ID;

@Override
public boolean onTouchEvent(MotionEvent ev) {
    // Let the ScaleGestureDetector inspect all events.
    mScaleDetector.onTouchEvent(ev);

    final int action = MotionEventCompat.getActionMasked(ev);

    switch (action) {
    case MotionEvent.ACTION_DOWN: {
        final int pointerIndex = MotionEventCompat.getActionIndex(ev);
        final float x = MotionEventCompat.getX(ev, pointerIndex);
        final float y = MotionEventCompat.getY(ev, pointerIndex);

        // Remember the starting position of the pointer.
        mLastTouchX = x;
        mLastTouchY = y;
        // Save the ID of this pointer for dragging.
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        break;
    }

    case MotionEvent.ACTION_MOVE: {
        // Find the index of the active pointer and fetch its position.
        final int pointerIndex =
                MotionEventCompat.findPointerIndex(ev, mActivePointerId);

        final float x = MotionEventCompat.getX(ev, pointerIndex);
        final float y = MotionEventCompat.getY(ev, pointerIndex);

        // Calculate the distance moved.
        final float dx = x - mLastTouchX;
        final float dy = y - mLastTouchY;

        mPosX += dx;
        mPosY += dy;

        invalidate();

        // Remember this touch position for the next move event.
        mLastTouchX = x;
        mLastTouchY = y;

        break;
    }

    case MotionEvent.ACTION_UP: {
        mActivePointerId = INVALID_POINTER_ID;
        break;
    }

    case MotionEvent.ACTION_CANCEL: {
        mActivePointerId = INVALID_POINTER_ID;
        break;
    }

    case MotionEvent.ACTION_POINTER_UP: {

        final int pointerIndex = MotionEventCompat.getActionIndex(ev);
        final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);

        if (pointerId == mActivePointerId) {
            // This is the active pointer going up. Choose a new
            // active pointer and adjust it accordingly.
            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
            mLastTouchX = MotionEventCompat.getX(ev, newPointerIndex);
            mLastTouchY = MotionEventCompat.getY(ev, newPointerIndex);
            mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
        }
        break;
    }
    }
    return true;
}

पैन करने के लिए खींचें और छोड़ें

पिछले सेक्शन में, स्क्रीन पर किसी ऑब्जेक्ट को खींचकर छोड़ने का उदाहरण दिया गया है. पैनिंग एक और आम स्थिति है. यह तब होता है, जब उपयोगकर्ता की स्क्रीन पर खींचने और छोड़ने की कार्रवाई से, X- और Y-ऐक्सिस, दोनों में स्क्रोल होता है. ऊपर दिया गया स्निपेट, खींचने और छोड़ने की सुविधा लागू करने के लिए, MotionEvent ऐक्शन को सीधे तौर पर इंटरसेप्ट करता है. इस सेक्शन में मौजूद स्निपेट, GestureDetector.SimpleOnGestureListener में onScroll() को बदलकर, प्लैटफ़ॉर्म में पहले से मौजूद सामान्य जेस्चर की सुविधा का फ़ायदा लेता है.

ज़्यादा जानकारी देने के लिए, जब कोई उपयोगकर्ता कॉन्टेंट को पैन करने के लिए उंगली को खींचता है, तो onScroll() को कॉल किया जाता है. onScroll() सिर्फ़ तब कॉल किया जाता है, जब उंगली नीचे हो. उंगली को स्क्रीन से हटाते ही, जेस्चर खत्म हो जाता है. अगर उंगली को हटाने से पहले, वह किसी रफ़्तार से चल रही थी, तो फ़्लिंग जेस्चर शुरू हो जाता है. स्क्रोल करने और फ़्लिंग करने के बारे में ज़्यादा जानकारी के लिए, स्क्रोल जेस्चर को ऐनिमेट करना लेख पढ़ें.

onScroll() के लिए कोड स्निपेट यह है:

Kotlin

// The current viewport. This rectangle represents the visible
// chart domain and range.
private val mCurrentViewport = RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX)

// The current destination rectangle, in pixel coordinates, into which the
// chart data must be drawn.
private val mContentRect: Rect? = null

private val mGestureListener = object : GestureDetector.SimpleOnGestureListener() {
    ...
    override fun onScroll(
            e1: MotionEvent,
            e2: MotionEvent,
            distanceX: Float,
            distanceY: Float
    ): Boolean {
        // Scrolling uses math based on the viewport, as opposed to math using
        // pixels.

        mContentRect?.apply {
            // Pixel offset is the offset in screen pixels, while viewport offset is the
            // offset within the current viewport.
            val viewportOffsetX = distanceX * mCurrentViewport.width() / width()
            val viewportOffsetY = -distanceY * mCurrentViewport.height() / height()


            // Updates the viewport and refreshes the display.
            setViewportBottomLeft(
                    mCurrentViewport.left + viewportOffsetX,
                    mCurrentViewport.bottom + viewportOffsetY
            )
        }

        return true
    }
}

Java

// The current viewport. This rectangle represents the visible
// chart domain and range.
private RectF mCurrentViewport =
        new RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX);

// The current destination rectangle, in pixel coordinates, into which the
// chart data must be drawn.
private Rect mContentRect;

private final GestureDetector.SimpleOnGestureListener mGestureListener
            = new GestureDetector.SimpleOnGestureListener() {
...

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
            float distanceX, float distanceY) {
    // Scrolling uses math based on the viewport, as opposed to math using
    // pixels.

    // Pixel offset is the offset in screen pixels, while viewport offset is the
    // offset within the current viewport.
    float viewportOffsetX = distanceX * mCurrentViewport.width()
            / mContentRect.width();
    float viewportOffsetY = -distanceY * mCurrentViewport.height()
            / mContentRect.height();
    ...
    // Updates the viewport, refreshes the display.
    setViewportBottomLeft(
            mCurrentViewport.left + viewportOffsetX,
            mCurrentViewport.bottom + viewportOffsetY);
    ...
    return true;
}

onScroll() को लागू करने पर, टच जेस्चर के जवाब में व्यूपोर्ट स्क्रोल होता है:

Kotlin

/**
 * Sets the current viewport, defined by mCurrentViewport, to the given
 * X and Y positions. The Y value represents the topmost pixel position,
 * and thus the bottom of the mCurrentViewport rectangle.
 */
private fun setViewportBottomLeft(x: Float, y: Float) {
    /*
     * Constrains within the scroll range. The scroll range is the viewport
     * extremes, such as AXIS_X_MAX, minus the viewport size. For example, if
     * the extremes are 0 and 10 and the viewport size is 2, the scroll range
     * is 0 to 8.
     */

    val curWidth: Float = mCurrentViewport.width()
    val curHeight: Float = mCurrentViewport.height()
    val newX: Float = Math.max(AXIS_X_MIN, Math.min(x, AXIS_X_MAX - curWidth))
    val newY: Float = Math.max(AXIS_Y_MIN + curHeight, Math.min(y, AXIS_Y_MAX))

    mCurrentViewport.set(newX, newY - curHeight, newX + curWidth, newY)

    // Invalidates the View to update the display.
    ViewCompat.postInvalidateOnAnimation(this)
}

Java

/**
 * Sets the current viewport (defined by mCurrentViewport) to the given
 * X and Y positions. Note that the Y value represents the topmost pixel
 * position, and thus the bottom of the mCurrentViewport rectangle.
 */
private void setViewportBottomLeft(float x, float y) {
    /*
     * Constrains within the scroll range. The scroll range is the viewport
     * extremes, such as AXIS_X_MAX, minus the viewport size. For example, if
     * the extremes are 0 and 10 and the viewport size is 2, the scroll range
     * is 0 to 8.
     */

    float curWidth = mCurrentViewport.width();
    float curHeight = mCurrentViewport.height();
    x = Math.max(AXIS_X_MIN, Math.min(x, AXIS_X_MAX - curWidth));
    y = Math.max(AXIS_Y_MIN + curHeight, Math.min(y, AXIS_Y_MAX));

    mCurrentViewport.set(x, y - curHeight, x + curWidth, y);

    // Invalidates the View to update the display.
    ViewCompat.postInvalidateOnAnimation(this);
}

स्केलिंग करने के लिए टच का इस्तेमाल करना

सामान्य जेस्चर का पता लगाना में बताए गए तरीके के मुताबिक, Android के इस्तेमाल किए जाने वाले सामान्य जेस्चर का पता लगाने के लिए, GestureDetector का इस्तेमाल करें. जैसे, स्क्रोल करना, फ़्लिंग करना, और टच करके रखना. स्केलिंग के लिए, Android ScaleGestureDetector उपलब्ध कराता है. अगर आपको किसी व्यू में अन्य जेस्चर की पहचान करनी है, तो GestureDetector और ScaleGestureDetector का एक साथ इस्तेमाल किया जा सकता है.

जेस्चर इवेंट का पता चलने पर, जेस्चर डिटेक्टर उनके कन्स्ट्रक्टर में पास किए गए, ऑब्जेक्ट के लिसनर का इस्तेमाल करते हैं. ScaleGestureDetector का इस्तेमाल करता है ScaleGestureDetector.OnScaleGestureListener. Android, ScaleGestureDetector.SimpleOnScaleGestureListener को हेल्पर क्लास के तौर पर उपलब्ध कराता है. अगर आपको रिपोर्ट किए गए सभी इवेंट की ज़रूरत नहीं है, तो इस क्लास को बढ़ाया जा सकता है.

स्केलिंग के बुनियादी उदाहरण

इस स्निपेट में, स्केलिंग से जुड़े बुनियादी एलिमेंट दिखाए गए हैं.

Kotlin

private var mScaleFactor = 1f

private val scaleListener = object : ScaleGestureDetector.SimpleOnScaleGestureListener() {

    override fun onScale(detector: ScaleGestureDetector): Boolean {
        mScaleFactor *= detector.scaleFactor

        // Don't let the object get too small or too large.
        mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f))

        invalidate()
        return true
    }
}

private val mScaleDetector = ScaleGestureDetector(context, scaleListener)

override fun onTouchEvent(ev: MotionEvent): Boolean {
    // Let the ScaleGestureDetector inspect all events.
    mScaleDetector.onTouchEvent(ev)
    return true
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)

    canvas?.apply {
        save()
        scale(mScaleFactor, mScaleFactor)
        // onDraw() code goes here.
        restore()
    }
}

Java

private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;

public MyCustomView(Context mContext){
    ...
    // View code goes here.
    ...
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    // Let the ScaleGestureDetector inspect all events.
    mScaleDetector.onTouchEvent(ev);
    return true;
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    canvas.scale(mScaleFactor, mScaleFactor);
    ...
    // onDraw() code goes here.
    ...
    canvas.restore();
}

private class ScaleListener
        extends ScaleGestureDetector.SimpleOnScaleGestureListener {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        mScaleFactor *= detector.getScaleFactor();

        // Don't let the object get too small or too large.
        mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));

        invalidate();
        return true;
    }
}

स्केलिंग का ज़्यादा मुश्किल उदाहरण

यहां स्क्रोल जेस्चर को ऐनिमेट करने में दिखाए गए InteractiveChart सैंपल से ज़्यादा मुश्किल उदाहरण दिया गया है. InteractiveChart सैंपल में, एक से ज़्यादा उंगलियों से स्क्रोल करने, पैन करने, और स्केल करने की सुविधाएं मिलती हैं. इसके लिए, ScaleGestureDetector स्पैन (getCurrentSpanX और getCurrentSpanY) और "फ़ोकस" (getFocusX और getFocusY) सुविधाओं का इस्तेमाल किया जाता है.

Kotlin

private val mCurrentViewport = RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX)
private val mContentRect: Rect? = null
...
override fun onTouchEvent(event: MotionEvent): Boolean {
    return mScaleGestureDetector.onTouchEvent(event)
            || mGestureDetector.onTouchEvent(event)
            || super.onTouchEvent(event)
}

/**
 * The scale listener, used for handling multi-finger scale gestures.
 */
private val mScaleGestureListener = object : ScaleGestureDetector.SimpleOnScaleGestureListener() {

    /**
     * This is the active focal point in terms of the viewport. It can be a
     * local variable, but keep it here to minimize per-frame allocations.
     */
    private val viewportFocus = PointF()
    private var lastSpanX: Float = 0f
    private var lastSpanY: Float = 0f

    // Detects new pointers are going down.
    override fun onScaleBegin(scaleGestureDetector: ScaleGestureDetector): Boolean {
        lastSpanX = scaleGestureDetector.currentSpanX
        lastSpanY = scaleGestureDetector.currentSpanY
        return true
    }

    override fun onScale(scaleGestureDetector: ScaleGestureDetector): Boolean {
        val spanX: Float = scaleGestureDetector.currentSpanX
        val spanY: Float = scaleGestureDetector.currentSpanY

        val newWidth: Float = lastSpanX / spanX * mCurrentViewport.width()
        val newHeight: Float = lastSpanY / spanY * mCurrentViewport.height()

        val focusX: Float = scaleGestureDetector.focusX
        val focusY: Float = scaleGestureDetector.focusY
        // Ensures the chart point is within the chart region.
        // See the sample for the implementation of hitTest().
        hitTest(focusX, focusY, viewportFocus)

        mContentRect?.apply {
            mCurrentViewport.set(
                    viewportFocus.x - newWidth * (focusX - left) / width(),
                    viewportFocus.y - newHeight * (bottom - focusY) / height(),
                    0f,
                    0f
            )
        }
        mCurrentViewport.right = mCurrentViewport.left + newWidth
        mCurrentViewport.bottom = mCurrentViewport.top + newHeight
        // Invalidates the View to update the display.
        ViewCompat.postInvalidateOnAnimation(this@InteractiveLineGraphView)

        lastSpanX = spanX
        lastSpanY = spanY
        return true
    }
}

Java

private RectF mCurrentViewport =
        new RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX);
private Rect mContentRect;
private ScaleGestureDetector mScaleGestureDetector;
...
@Override
public boolean onTouchEvent(MotionEvent event) {
    boolean retVal = mScaleGestureDetector.onTouchEvent(event);
    retVal = mGestureDetector.onTouchEvent(event) || retVal;
    return retVal || super.onTouchEvent(event);
}

/**
 * The scale listener, used for handling multi-finger scale gestures.
 */
private final ScaleGestureDetector.OnScaleGestureListener mScaleGestureListener
        = new ScaleGestureDetector.SimpleOnScaleGestureListener() {
    /**
     * This is the active focal point in terms of the viewport. It can be a
     * local variable, but keep it here to minimize per-frame allocations.
     */
    private PointF viewportFocus = new PointF();
    private float lastSpanX;
    private float lastSpanY;

    // Detects new pointers are going down.
    @Override
    public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) {
        lastSpanX = ScaleGestureDetectorCompat.
                getCurrentSpanX(scaleGestureDetector);
        lastSpanY = ScaleGestureDetectorCompat.
                getCurrentSpanY(scaleGestureDetector);
        return true;
    }

    @Override
    public boolean onScale(ScaleGestureDetector scaleGestureDetector) {

        float spanX = ScaleGestureDetectorCompat.
                getCurrentSpanX(scaleGestureDetector);
        float spanY = ScaleGestureDetectorCompat.
                getCurrentSpanY(scaleGestureDetector);

        float newWidth = lastSpanX / spanX * mCurrentViewport.width();
        float newHeight = lastSpanY / spanY * mCurrentViewport.height();

        float focusX = scaleGestureDetector.getFocusX();
        float focusY = scaleGestureDetector.getFocusY();
        // Ensures the chart point is within the chart region.
        // See the sample for the implementation of hitTest().
        hitTest(scaleGestureDetector.getFocusX(),
                scaleGestureDetector.getFocusY(),
                viewportFocus);

        mCurrentViewport.set(
                viewportFocus.x
                        - newWidth * (focusX - mContentRect.left)
                        / mContentRect.width(),
                viewportFocus.y
                        - newHeight * (mContentRect.bottom - focusY)
                        / mContentRect.height(),
                0,
                0);
        mCurrentViewport.right = mCurrentViewport.left + newWidth;
        mCurrentViewport.bottom = mCurrentViewport.top + newHeight;
        ...
        // Invalidates the View to update the display.
        ViewCompat.postInvalidateOnAnimation(InteractiveLineGraphView.this);

        lastSpanX = spanX;
        lastSpanY = spanY;
        return true;
    }
};

अन्य संसाधन

इनपुट इवेंट, सेंसर, और कस्टम व्यू को इंटरैक्टिव बनाने के बारे में ज़्यादा जानने के लिए, नीचे दिए गए रेफ़रंस देखें.