I'm writing an application draws in another application's window (this is under OS X with Cocoa, but the question is general enough that I hope it won't be bogged down by operating system / framework issues), and I'm running into a problem which seems like it should have a simple answer, but it's driving me absolutely insane. Here's the problem:
I draw a rectangle inside another application's window which has to be in a certain location relative to the top and left of the window (i.e. the margins between my rectangle and the top & left of the target window must remain fixed). I can calculate the relative x,y coordinates required as a percentage of the window's size, which works fine: the rectangle shows up correctly. However, the user then resizes the window, and I can resize the rectangle correctly by using a transformation based on the ratio of the new height and width to the old height and width, but I lose my relative positioning: the rectangle's coordinates are now incorrect (see image - this is a rough mockup of the problem).
image http://img30.imageshack.us/img30/5273/resizeexample.png
Now, I can't figure out how to calculate the new x,y coordinates relative to the top and left of the window. The window isn't square; its resize is constrained by the other application, but the aspect ratio width / height changes by some unknown function. When I measure the required y coordinates in relative terms, the percentage changes when the window resize. Numerically, it looks something like this:
Before resize:
window size: h=>760, w=>546
rectangle origin: x=>355, y=>84 (e.g. 84/546 = 15.3% of height)
After resize:
window size: h=>1009, w=>717
rectangle origin should be: ? (I can measure it as something like x=>474,y=>99, but I can't predict those values; 99/717 now = 13.8% of height).
I've tried every ratio of the two windows' measurements I can think of; I've also run across the idea of translating to the origin, scaling, and then translating back to avoid the problem of scaling moving the coordinates - but I don't know where to translate back to! This probably has some simple geometric / trigonometric solution, but nothing occurs to me no matter how many diagrams I draw. I'm willing to accept the inevitable embarrassment of someone pointing out some one-line solution to this problem if they can just point me in the right direction here!