Sort rectangles in a grid based on a comparison of the center point of each
- by Mrwolfy
If I have a grid of rectangles and I move one of the rectangles, say above and to the left of another rectangle, how would I resort the rectangles?
Note the rectangles are in an array, so each rectangle has an index and a matching tag. All I really need to do is set the proper index based on the rectangles new center point position within the rectangle, as compared with the center point position of the other rectangles in the grid. Here is what I am doing now in pseudo code (works somewhat, but not accurate):
-(void)sortViews:myView {
int newIndex;
// myView is the view that was moved.
[viewsArray removeObject:myView];
[viewsArray enumerate:obj*view]{
if (myView.center.x > view.center.x) {
if (myView.center.y > view.center.y) {
newIndex = view.tag -1;
*stop = YES;
} else {
newIndex = view.tag +1;
*stop = YES;
}
} else if (myView.center.x < view.center.x) {
if (myView.center.y > view.center.y) {
newIndex = view.tag -1;
*stop = YES;
} else {
newIndex = view.tag +1;
*stop = YES;
}
}
}];
if (newIndex < 0) {
newIndex = 0;
} else if (newIndex > 5) {
newIndex = 5;
}
[viewsArray insertObject:myView atIndex:newIndex];
[self arrangeGrid];
}