Area of intersection between two squares

Given a grid of squares, I need to figure out how, when a player places an object with a square footprint, to calculate what percentage of that footprint is in each grid square. Put more simply, how do I calculate the area of intersection of two squares.

I know how elementary this seems, but I don’t want to have to write a bunch of conditional statements that seem to be necessary given that the math changes somewhat based on the position of one square relative to another.

For example, assuming no rotation of either square, if the upper left quadrant of square B intersects square A in A’s lower right quadrant, then, to get the area, it would be (A.xMax-B.xMin)*(A.yMax-B.yMin). But, if the intersetion occurs in the upper left quadrant of B and the lower right quad of A, the math changes somewhat.

I’m looking for a solution that works regardless of where one square intersects the other. Furthermore, I need one that will handle the eventuality that square B will be rotated such that the respective sides of the two squares are not parallel.

Arbitrary rotated intersecting squares / rectangles will produce an irregular shaped area with either 3, 4 or 5 corners. There’s no easy way to do this in a single-line-formular.

Even calculating the shape (corners) of the intersection area is some hard work. To calculate the area of such a polygon isn’t much easier. You have to divide the polygon into primitive shapes (mostly triangles) but that’s also not as easy as it sounds.

Before doing something like that you should ask yourself if you really need it. For what purpose do you need that percentage value and how accurate do you need it.

A far easier way would be to approximate the value by subdividing your squares into some kind of voxel / point-mass grid and just count the points that are inside the testing square.