简体   繁体   中英

How can I find every pixel on a line with pygame?

Assuming I have a line with coordinates x1,y1 and x2,y2, and I know the length of the hypotenuse connecting those two points (thus also knowing the angle of rotation of the line through trig), if the line is 1 pixel thick how can I find every pixel on that line and store it to a list?

I first proposed the simple vector calculation, stating with x1,y1 and performing line/z*math.cos(angle),line/z*math.sin(angle) (for x1 and y1 respectively) until I reached point x2,y2, but the problem with that is finding variable 'z' such that every single pixel is covered without duplicating pixels.

So what would be the best way of calculating this?

Using float you should get all points without duplications - but you need int .

Using int you always get duplications - int(0.1) == int(0.2) == int(0.3) == etc. .

So you have to check if point is on your list.

This is what Bresenham's line algorithm is for. In order to use it properly, you should first figure out which is your major axis (whether the line is longer in Y or in X). Then for every integer location along the major axis, you calculate whether the value for the minor axis stays the same or increments (+1 or -1, depending on slope).

There are several explanations of this online -- this one is in Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM