I have a point array and a panel. getWidth() is based off the panel. Imagine cards in your hand, so HAND_CARD_WIDTH is pretty self explanatory. The purpose of this loop is to set the points evenly across the panel, which it does. However, it allow the cards to go out of the panel, which makes it look very bad. What I want to do is give a small empty margin on both sides of the panel no matter how many cards you have in your hand.
Here’s the code
int iteration = 1;
int limiter = getWidth();
int slice = (limiter/(handsize+1));
while (points.size() < handsize) {
int x = slice*(iteration++);
x -= HAND_CARD_WIDTH/2;
points.add(new Point(x, y));
}
Basically I want the leftmost x to be at least 20 and the rightmost to be at most getWidth() - 20 - HAND_CARD_WIDTH. I also want the cards to be evenly spaced… I just can’t think of the right equation (getting to this point was sadly a feat..).
Thanks, based on the responses (all 2 of them) heres what I went with:
if((int)points.get(0).getX() < margin){
int boost = Math.abs(margin - (int)points.get(0).getX());
slice = (boost*2)/handsize;
for(Point p : points){
p.x += boost;
boost -= slice;
}
}
Not sure if I understand your layout, but I think it is something like this:
or
So, the number of spaces is one more than number of cards and the total width is component width minus margins. componentWidth = numCards x cardWidth + (numCards + 1) x spaceWidth Now it is easy to calculate the space needed which is (componentWidth – numCards x cardWidth) / (numCards + 1) so the left position of a card is leftMargin + spaceWidth x cardNum + cardWidth x (cardNum – 1)
Care must be taken when the space is negative, then you instead must calculate how much the cards must overlap.