RajaReddy PolamReddy
RajaReddy PolamReddy

Reputation: 22493

How to scroll the bitmap with two fingers?

Can anybody tell me how to scroll a bitmap with two fingers, because in my app I am using one finger to paint. Since I want to paint an entire image (it may be larger than the screen) scrolling with two fingers would be convenient?

Upvotes: 1

Views: 957

Answers (1)

Pavel Smolensky
Pavel Smolensky

Reputation: 86

private class Img extends View {
    private Bitmap bmp;
    private Rect imgRect, scrollRect;
    private float prevX, prevY;
    private int newX, newY;

    public Img(Context context) {
        super(context);
        bmp = BitmapFactory.decodeResource(getResources(),
                R.drawable.screen);
        imgRect = new Rect(0, 0, width, height);
        scrollRect = new Rect(0, 0, width, height);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_MOVE: {
            int numPointers = event.getPointerCount();
            if (numPointers > 1) {
                float currX = event.getRawX();
                float deltaX = -(currX - prevX);
                newX += deltaX;
                float currY = event.getRawY();
                float deltaY = -(currY - prevY);
                newY += deltaY;
                if (newX < 0)
                    newX = 0;
                if (newY < 0)
                    newY = 0;
                if (newX > bmp.getWidth() - width)
                    newX = bmp.getWidth() - width;
                if (newY > bmp.getHeight() - height)
                    newY = bmp.getHeight() - height;
                scrollRect.set(newX, newY, newX + width, newY + height);
                invalidate();
                prevX = currX;
                prevY = currY;
            }
            break;
        }
        case MotionEvent.ACTION_DOWN: {
            prevX = event.getRawX();
            prevY = event.getRawY();
            break;
        }
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(bmp, scrollRect, imgRect, new Paint());
    }
}

Here Img class represents the View with a large bitmap, which displays its currently visible rectangle. int numPointers = event.getPointerCount(); if (numPointers > 1) { - and here you get number of fingers, that touch the screen. So if it is greater than 1, large image will be scrolled, otherwise, you can implement your paint logic.

Upvotes: 3

Related Questions