如何限制图像的拖动区域?

时间:2015-12-14 09:29:03

标签: android imageview drag ontouchlistener

这是我的代码:

public class FullScreenImageView extends Activity {

ImageView mAttachmentView;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();

static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

private float dx; // postTranslate X distance
private float dy; // postTranslate Y distance
private float[] matrixValues = new float[9];
float matrixX = 0; // X coordinate of matrix inside the ImageView
float matrixY = 0; // Y coordinate of matrix inside the ImageView
float width = 0; // width of drawable
float height = 0; // height of drawable

// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
String savedItemClicked;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fullscreenimageview);

    Bundle bundle = getIntent().getExtras();
    byte[] imageByteArray = bundle.getByteArray("attachmentPreview");

    Bitmap bitmap = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);

    mAttachmentView = (ImageView) findViewById(R.id.FullScreenImageView_AttachmentView);
    mAttachmentView.setImageBitmap(bitmap);

   mAttachmentView.setOnTouchListener(mAttachmentViewOnTouch);
}


private View.OnTouchListener mAttachmentViewOnTouch = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub

        ImageView view = (ImageView) v;
        dumpEvent(event);

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                start.set(event.getX(), event.getY());
                mode = DRAG;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                if (oldDist > 10f) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                }
                break;
            case MotionEvent.ACTION_UP:

            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                break;

            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    matrix.set(savedMatrix);
                    matrix.postTranslate(event.getX() - start.x,event.getY()
                            - start.y);
//This doesn't work for sure, but how can I control this?

如何控制拖动区域?我应该创建一个framelayout并检查矩阵x和y何时超出framelayout的宽度和高度然后停止?但我怎么能这样做?请帮忙。

0 个答案:

没有答案