Calculating the position of QR Code alignment patterns

前端 未结 5 1509
陌清茗
陌清茗 2021-01-13 05:25

I need to know how to calculate the positions of the QR Code alignment patterns as defined in the table of ISO/IEC 18004:2000 Annex E.

I don\'t understand how it\'s

5条回答
  •  别那么骄傲
    2021-01-13 06:14

    There are some comments on the top rated answer that suggest it isn't 100% accurate, so i'm contributing my solution as well.

    My solution is written in C#. It should be easy to translate it to a language of your choice.

    private static int[] getAlignmentCoords(int version)
        {
            if (version <= 1)
            {
                return new int[0];
            }
    
            int num = (version / 7) + 2;//number of coordinates to return
            int[] result = new int[num];
    
            result[0] = 6;
    
            if (num == 1)
            {
                return result;
            }
    
            result[num - 1] = 4 * version + 10;
    
            if (num == 2)
            {
                return result;
            }
    
            result[num - 2] = 2 * ((result[0] + result[num - 1] * (num - 2)) / ((num - 1) * 2)); //leave these brackets alone, because of integer division they ensure you get a number that's divisible by 2
    
            if (num == 3)
            {
                return result;
            }
    
            int step = result[num - 1] - result[num - 2];
    
            for (int i = num - 3; i > 0; i--)
            {
                result[i] = result[i + 1] - step;
            }
    
            return result;
        }
    

    The values i get with it are the same as shown here: http://www.thonky.com/qr-code-tutorial/alignment-pattern-locations/

    To sum it up, the first coordinate is always 6.

    The last coordinate is always 7 less than the image size. The image size is calculated as 4*version+17, therefore the last coordinate is 4*version+10.

    If the coordinates were precisely evenly spaced, the position of one coordinate before the last would be (first_coordinate+(num-2) * last_coordinate)/(num-1), where num is the number of all coordinates. But the coordinates are not evenly spaced, so this position has to be reduced to an even number.

    Each of the remaining coordinates is spaced the same distance from the next one as the last two are from each other.

    Disclaimer: I didn't read any of the documentation, i just wrote some code that generates a sequence of numbers that's the same as in the table i linked to.

提交回复
热议问题