Pergunta

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;
            }
        }
Foi útil?

Solução

Not sure if I understand your layout, but I think it is something like this:

|margin|space|card|space|card|space|margin|

or

|margin|space|card|space|margin|

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.

Outras dicas

Try this:

final int MARGIN = 20;
int availableWidth = getWidth() - 2 * MARGIN - HAND_CARD_WIDTH;
int cardSpaceWidth = availableWidth / handsize;
for (int i = 0; i < handsize; i++) {
    int x = MARGIN + ((i + 0.5) * cardSpaceWidth) - HAND_CARD_WIDTH / 2;
    points.add(new Point(x, y));
}

So:

  • calculate the available width by subtracting the margins from total panel width
  • calculate the space for each card by dividing remaining space by number of cards
  • for each card, we count its leftmost point by taking the middle of card space and subtracting half the width of the card.

Mind you, with this solution cards still can overlap margins, if HAND_CARD_WIDTH is greater than available space for card.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top