Sort rectangles in a grid based on a comparison of the center point of each
Posted
by
Mrwolfy
on Programmers
See other posts from Programmers
or by Mrwolfy
Published on 2013-09-17T05:33:03Z
Indexed on
2013/10/17
22:19 UTC
Read the original article
Hit count: 188
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];
}
© Programmers or respective owner