algorithm - Given aspect ratio of a rectangle, find maximum scale and angle to fit it inside another rectangle -
i've read few dozen questions on topic, none seem i'm looking for, i'm hoping isn't duplicate.
i have image, aspect ratio want maintain, because it's image.
i want find largest scale factor, , corresponding angle between 0 , 90 degrees inclusive, such image fit wholly inside given rectangle.
example 1: if image , rectangle same ratio, angle 0, , scale factor ratio of rectangle's width image's width. (or height-to-height.)
example 2: if image , rectangle ratios inverse of each other, scale factor same first example, angle 90 degrees.
so, general case, given image.width, image.height, rect.width, rect.height, how find image.scale , image.angle?
ok, figured out on own.
first, calculate aspect ratio. if image 1:1, there's no point in this, because angle zero, , scale min(width, height). degeneration.
otherwise, can use this:
// assuming below width , height rectangle's _imageaspect = _image.width / _image.height; if (_imageaspect == 1) { // div 0 implied trace( "square image...this not lend rotation ;)" ); return; } _imageaspectsq = math.pow( _imageaspect, 2 ); var rotate:float; var newheight:float; if (width > height && width / height > _imageaspect) { // wider aspect image newheight = height; rotate = 0; } else if (height > width && height / width > _imageaspect) { // skinnier aspect image rotated 90 degrees newheight = width; rotate = math.pi / 2; } else { var hprime = (_imageaspect * width - _imageaspectsq * height) / ( 1 - _imageaspectsq ); var wprime = _imageaspect * (height - hprime); rotate = math.atan2( hprime, wprime ); var sine = math.sin(rotate); if (sine == 0) { newheight = height; } else { newheight = (width - wprime) / sine; } }
the first 2 cases degenerate: image's aspect ratio less rectangle. similar square-within-a-rectangle case, except in case, square always degenerate.
the code assumes radians instead of degrees, it's not hard convert.
(also i'm bit shocked browser's dictionary didn't have 'radians'.)
Comments
Post a Comment