Aspect ratio and image fitting.

BlitzMax Forums/BlitzMax Beginners Area/Aspect ratio and image fitting.

Ryan Burnside(Posted 2009) [#1]
Hello, recently I've run into a difficult problem.

I need to fit an image inside a rectangle or arbitrary dimensions and maintain the aspect ratio of the image. Given the width and height of the frame, and the width and height of the image, how do I find the best fit while maintaining the aspect ratio of the image? I just want to draw the sprite so it will best fit the viewing frame. The problem is that the images may be taller than they are wide or wider than they are tall.




so I have a function that looks like this

draw_picture(frame_x:int,frame_y:int,frame_width:float, frame_height:float, image:timage)



GfK(Posted 2009) [#2]
The getDimensions() function is the useful bit - the rest is really just to demonstrate. Change the values of frameWidth and frameHeight to test.

PS: I've tested the speed of getDimensions() and it can run 10,000 iterations in 2ms.
Strict

Graphics 800,600
SetBlend SOLIDBLEND

Global framex:Int = 100
Global framey:Int = 100
Global frameWidth:Int = 450
Global frameHeight:Int = 150

Global img:TImage = LoadImage("cut1.jpg")
Global width:Float,height:Float

getdimensions()

While Not AppTerminate()
	Cls
	drawFrame()
	DrawImageRect img,framex,framey,width,height
	Flip
Wend
End

Function drawFrame()
	SetColor 255,0,0
	DrawRect framex,framey,framewidth,frameheight 
	SetColor 255,255,255
End Function

Function getDimensions()
	Local ratio:Float
	width = frameWidth
	ratio = width / img.width
	height = img.height * ratio
	
	If width <=frameWidth And height <= frameHeight
		Return
	EndIf
	
	height = frameHeight
	ratio = height / img.height
	width = img.width * ratio
End Function



Ryan Burnside(Posted 2009) [#3]
Thanks GfK. :)