Function for rotating the TouchScreen matrix to match Display orientation.

Ok, so I ran into an issue when I rotated Display that repositioned the Button images but not the touchscreen coordinates. So the button hotspots did not remap. Thankfully I fingered out a way to recalculate the screen touch coordinates so that they line up with the Display orientation.

I have this setup as a function that can be used to replace .touch_point when figuring out what part of the screen was touched. This function will look at the size that we set for the Touchscreen as well as the rotation that we set for display. Based on that information it will recalculate the same relative position based on where the screen was touched.

This function assumes that you have set up the display and touchscreen like the following:

display = board.DISPLAY
display.rotation=90

# Touchscreen setup
ts = adafruit_touchscreen.Touchscreen(board.TOUCH_XL, board.TOUCH_XR,
                                      board.TOUCH_YD, board.TOUCH_YU,
                                      calibration=((5200, 59000), (5800, 57000)),
                                      size=(320, 240))

Next you will want to add the following function to your code.

### Function for recalculating .touch_point based on Display rotation
def touch_rotate():
    touchData = ts.touch_point
    if touchData:
        if display.rotation == 0:
            return touchData
        elif display.rotation == 90:
            touchX = adafruit_touchscreen.map_range(touchData[0], 0, ts._size[0], ts._size[0], 0)
            return (touchData[1],int(touchX) )
        elif display.rotation == 180:
            touchX = adafruit_touchscreen.map_range(touchData[0], 0, ts._size[0], ts._size[0], 0)
            touchY = adafruit_touchscreen.map_range(touchData[1], 0, ts._size[1], ts._size[1], 0)
            return (int(touchX), int(touchY))
        elif display.rotation == 270:
            touchY = adafruit_touchscreen.map_range(touchData[1], 0, ts._size[1], ts._size[1], 0)
            return (int(touchY),touchData[0] )

To use this you will call touch_rotate() when you need to know where the screen was touched rather than using ts.touch_point

This is most useful for the onscreen buttons.