Does anyone know if there is a simple way to make images snap to grid when dragging a bitmap?
At the moment I can touch a bitmap and move it smoothly around the screen. I want to be able to make it snap to an invisible grid whilst you are dragging.
It's what I do in an application I'm just finishing at the moment. When the user is dragging something on the screen, I display a visible snap grid, and the object is snapped to that grid when the dragging has finished. To show a grid, my approach is to use a separate custom View
that I named GridOverLayView
. It is overlaid over the entire screen area and it very simply draws a snap grid in its onDraw()
method. It is made visible only when something is being dragged.
Now, concerning the actual Activity
in which dragging and dropping is handled, one particular constant I've defined is:
static final int SNAP_GRID_INTERVAL = 20;
When the object is being dragged around, i.e. when processing event.getAction()==MotionEvent.ACTION_MOVE
events within my OnTouchListener
, I perform snapping of the object's location to grid using the following:
RelativeLayout.LayoutParams par = (RelativeLayout.LayoutParams) mThingBeingDragged.getLayoutParams();
par.topMargin = Math.round((event.getRawY() - draggedInitialY) / SNAP_GRID_INTERVAL ) * SNAP_GRID_INTERVAL;
par.leftMargin = Math.round((event.getRawX() - draggedInitialX) / SNAP_GRID_INTERVAL ) * SNAP_GRID_INTERVAL;
mThingBeingDragged.setLayoutParams(par);
...where draggedInitialY
and draggedInitialX
store the initial touch position recorded during the initial MotionEvent.ACTION_DOWN
.
A further nice touch is to allow the object being dragged to be moved around without snapping, but have it snap to the grid only in the .ACTION_UP
when the user lifts their finger. In practice, this feels much nicer to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With