如何用两个手指滚动位图?

时间:2011-08-22 11:22:16

标签: android bitmap

任何人都可以告诉我如何用两根手指滚动位图,因为在我的应用程序中我用一根手指画画。由于我想要绘制整个图像(可能比屏幕大),用两根手指滚动会很方便吗?

1 个答案:

答案 0 :(得分:3)

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());
    }
}

这里Img类用大位图表示视图,该位图显示当前可见的矩形。 int numPointers = event.getPointerCount(); if (numPointers > 1) { - 在这里,您可以获得触摸屏幕的手指数量。因此,如果它大于1,则会滚动大图像,否则,您可以实现绘制逻辑。