2

我是否误解了如何翻译和缩放画布?我创建了一个可以拖动和缩放的自定义视图,但它在我设置的范围内。我认为翻译画布会重新绘制边界?我希望能够在整个屏幕上拖动和缩放图像,而不是在视口中!我假设翻译画布会调整视口。

我在想这个错误的方式吗?

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    canvas.translate(mPosX, mPosY);
    canvas.scale(mScaleFactor, mScaleFactor);
    mIcon.draw(canvas);
    canvas.restore();
}

这就是我创建视图的方式。所以基本上它卡在这个 250 x 250 的盒子里。我需要实际拖动视图。我觉得我在做一些愚蠢的事情,但我无法产生我正在寻找的行为。

    MultiTouchImageView view = new MultiTouchImageView(this);
    view.setLayoutParams(new RelativeLayout.LayoutParams(250, 250));
4

1 回答 1

1

您可以设置边距以在布局中移动视图。我创建了测试项目来展示这个想法,它看起来像这样:

public class DragView extends View {

    private float mLastTouchX;
    private float mLastTouchY;

    private float mDeltaX;
    private float mDeltaY;

    public DragView(Context context) {
        super(context);
        init();
    }

    public DragView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final int action = event.getAction();

                mLastTouchX = event.getRawX();
                mLastTouchY = event.getRawY();

                switch (action) {
                case MotionEvent.ACTION_DOWN: {
                    RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) getLayoutParams();
                    mDeltaX = mLastTouchX - lParams.leftMargin;
                    mDeltaY = mLastTouchY - lParams.topMargin;

                    break;
                }
                case MotionEvent.ACTION_MOVE: {
                    mLastTouchX = event.getRawX();
                    mLastTouchY = event.getRawY();

                    final RelativeLayout.LayoutParams params = (LayoutParams) getLayoutParams();
                    params.leftMargin = (int) (mLastTouchX - mDeltaX);
                    params.topMargin = (int) (mLastTouchY - mDeltaY);
                    setLayoutParams(params);

                    break;
                }
                }

                return true;
            }
        });
    }

}
于 2013-09-24T04:32:14.363 回答