Andrei Freeman (lordandrei) wrote,
Andrei Freeman
lordandrei

  • Mood:

Math is fun?

Cross posted in macosxdev and my home journal

Warning, this is all math and geometry... turn around and back away slowly if you value your life :)

I am posting this mainly for external validation. I think I have the concept right but my geometry is just a little rusty.

I am currently working on a resize algorithm. I have a maximum box size of W x H.
Now, if given a box that is W+Y x H+Z where Y and Z are some arbitrary overage to the Width and Height, I need to scale this box to (no larger than) W x H while retaining the boxes original ratio.

For the purpose of illustration W > H
My box can not be bigger than 80x40 and I've been handed a box 100x60.

My theory is: to scale this correctly I need to find the greater of Y and (Z * W/H)

I have to apply a "max size ratio" because the fact that the overage is equal in length doesn't necessarily mean it is equal in relation to the length of the side's maximum. In my example both sides have an overage of 20 but the height is 50% over the height max while the width is only 25%. By applying the max size ratio, the % differences equal out so an equal percent scale would bring both sides within the needed parameters.

Once the greater is discovered, a scaleRatio can be computed by:
sr = side / (side + side's overage)

This scaleRatio can now be applied to each side of the given box.

As for the code. Yes, this is in objective-C. I don't know if I am reinventing some wheel that is in one of the frameworks. I had a problem and I did what I can to solve it. I'm curious if this solution is viable or if people have other solutions. Also, wanted to post the thinking and code for an algorithm for people who are interested in seeing such things.

typedef struct _NSSize {
    float width;
    float height;
} NSSize;
extern NSSize  kMaxSize;

-(NSSize) scaleToMaxSize:(NSSize)someSize
{
  NSSize    retSize = someSize;

  if ((someSize.height > kMaxSize.height) || (someSize.width > kMaxSize.width)) {
    float    heightOverage = someSize.height - kMaxSize.height;
    float    widthOverage = someSize.width - kMaxSize.width;
    float    scaleRatio=0.0;
		
    if (heightOverage * (kMaxSize. width * kMaxSize.height) > widthOverage) {
      scaleRatio = kMaxSize.height / someSize.height;
    } else {
      scaleRatio = kMaxSize.width / someSize. width;
    }

    if (scaleRatio > 0.0) {
      retSize.heigth *= scaleRatio;
      retSize.width *= scaleRatio;
    }

  return retSize;
}


Thanks.
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 1 comment