# Technology Musings

### Snippets / Calculating an Even Baseline

JB

So, I've been working in Xamarin for cross-platform phone development.  I was using their AbsoluteLayout class to try to get a bar graph working using relative sizes (AbsoluteLayout with relative sizes gives everything an absolute position from 0, top or left of the screen, to 1, the bottom or right of the screen).  The goal was to have the bottom of the bar graph halfway down the screen (to allow room for negative values to point down).  The goal was to look like this:

The problem, though is getting the boxes to align at the center line.  Now, part of the problem may be my inexperience with the platform.  There may be a really easy way to do this.  However, here is what I was running into:

I thought that Xamarin worked by aligning the your specified position to the middle of the box.  Therefore, I started by calculated the box height, and then calculating the origin of the box by setting it above the 0.5 (i.e., 50%) line by half of the box height.  Therefore, when it extended, it should extend down to the 0.5 line.

The problem, though, is that Xamarin doesn't  align to the middle of the box.  It varies the alignment by where in the positioning it is positioned.  So, if you position a box at 0.2, not only is it positioned at 0.2, but the anchoring point is also 0.2 down the box!

Therefore, I needed a way to calculate where I needed to actually position the box to get it to rest on the 0.5 line.

The way I calculated it is this - let's call the y-position that you want the box to rest on as P.  Let's call the y-position which you are going to set your box to as A (for the anchoring position).  Let's call the height of the box itself H.

What we want to happen is for the bottom of the box to hit P.

Now, we can split up the measurements from the top of the box to P into two lengths - the length from the top to the anchoring point (which is actually just A) and the length from the anchoring point to the bottom of the box.

Since the anchoring point sits A down on the box, the length of the top half of the box is given by A*H.  However, this is not the distance we want.  We want the distance down the rest of the box.  That will be (1 - A)*H.

So, our two distances are: A and (1 - A)*H.  They should add together to be P.  Therefore, our equation is:

A + (1 - A)*H = P

However, we want to solve this for A - we already know our box height (H), and we know what position we want this to extend to (P).  Therefore, we have to solve for A:

A + (1 - A)*H = P
A + H - A*H = P
A - A*H = P - H
A*(1 - H) = P - H
A = (P - H) / (1 - H)

And this gives a perfect calculation for A.  In my case, since P is 0.5, I just do A = (0.5 - H) / (1 - H) and it comes out perfectly.

It should be fairly simple to come up with similar calculations for top alignment and center alignment.  Additionally, these work with right-to-left alignments as well.