I've setup a basic 2d renderer that works pretty well so far but now I've started running into viewport scaling issues when testing different screen sizes.

Typically my projects are designed for a particular resolution and aspect ratio.

Say I design for a 1024x768 or 16:9 aspect ratio.

If my application is running on a 16:9 device things look fine, on any other aspect ratio things get distorted.

my current solution is trying to setup a virtual viewport WxH and an actual viewport WxH

I'll use the virtual width, height to get a target aspect ratio like this:
aspect_ratio = virtual_width / virtual_height;

then I get the width and height like this:
width = actual_width;
height = width / aspect_ratio;

this is where I am having some issues.

Let's say that I designed my app to run at 1024x768 but I want to match the width and scale the height or I want to match the height and scale the width.

How can I do that?

Also one additional question when I get letterboxing, what if I want to draw some larger image in the background so instead of just having black bars I can have some art back there.

What are the steps required to do that as well?