The Xojo Blog recently put up a post with a snippet of code for centering a picture inside a Graphics object. I figured I'd present a simpler way to solve the problem.

``````Public Sub CenterPicture(Extends Target As Graphics, Pic As Picture)
If Pic Is Nil Then
Return
End If

// We need the smallest ratio. Limit to a max of 1.0 to prevent scaling up.
Var Ratio As Double = Min(Target.Width / Pic.Width, Target.Height / Pic.Height, 1.0)

// Despite Graphics accepting Doubles now, use Integer for improved sharpness.
// More advanced code would round to a factor evenly divisible by the scale factor of Target.
// Don't use Round, because one dimension might round differently than the other. Use Floor or Ceil.
Var Width As Integer = Floor(Pic.Width * Ratio)
Var Height As Integer = Floor(Pic.Height * Ratio)

// Now it's simple math to center it
Var Left As Integer = Floor((Target.Width - Width) / 2)
Var Top As Integer = Floor((Target.Height - Height) / 2)

// And draw it
Target.DrawPicture(Pic, Left, Top, Width, Height, 0, 0, Pic.Width, Pic.Height)
End Sub``````

Much more to the point.

If you're adventurous, try adding a parameter to specify the scaling mode. You could add options such as "no scaling" and "fill" instead. All you need to do is change how the ratio is selected.