StoneCodeMonkey
Well-known member
- Joined
- Apr 17, 2009
- Messages
- 56
- Programming Experience
- 5-10
I have been using the same basic code to calculate the scale factor to fit one rectangle within another for some time now. After posting a few replys on how to do this, in various forms, I decided to go back and see if there is a better way. But, I keep coming back to the same methods.
Does anyone know a better method to do this other than the following code while maintaining the aspect ratio?
Does anyone know a better method to do this other than the following code while maintaining the aspect ratio?
VB.NET:
Function ScaleToFit(ByVal DestinationRectangle As Rectangle, ByVal RectangleToScale As Rectangle) As Rectangle
Dim pOrigin As Point = New Point(DestinationRectangle.Left, DestinationRectangle.Top)
Dim pSize As Size = New Size(DestinationRectangle.Width, DestinationRectangle.Height)
Dim wRatio As Single = pSize.Width / RectangleToScale.Width
Dim hRatio As Single = pSize.Height / RectangleToScale.Height
Dim ScaleToWidth As Boolean = False
Dim ScaleToHeight As Boolean = False
If wRatio < hRatio Then
'Scale to the width ratio
ScaleToWidth = True
Else
'Scale to the height ratio
ScaleToHeight = True
End If
Dim sizePrint As Size
If RectangleToScale.Width < pSize.Width AndAlso RectangleToScale.Height < pSize.Height Then
sizePrint = New Size(RectangleToScale.Width, RectangleToScale.Height)
Else
If ScaleToWidth Then
sizePrint = New Size(RectangleToScale.Width * wRatio, RectangleToScale.Height * wRatio)
ElseIf ScaleToHeight Then
sizePrint = New Size(RectangleToScale.Width * hRatio, RectangleToScale.Height * hRatio)
End If
End If
sizePrint.Height -= 1
sizePrint.Width -= 1
'Just centers the rectangle within the destination rectangle
Dim loc As Point
loc = New Point(pOrigin.X + ((pSize.Width - sizePrint.Width) / 2), pOrigin.Y + ((pSize.Height - sizePrint.Height) / 2))
Return New Rectangle(loc, sizePrint)
End Function