Sunday, October 14, 2007

Targeting both VGA and QVGA Screens

I have written some previous articles on GDI about one thing or another in the past, but never mentioned the simple practice of ensuring your code will display correctly under all screen types. Even though the code I have posted contains this practice I have never made a point of it.
It is very simple. Carry out the following steps:

1. Declare a constant that defines the points per inch you intend to design your control. In the example below, I have used 96dpi which is a QVGA screen (320x240) which is the majority of devices on the market today.


private int DESIGNPOINTSPERINCH = 96;



2. The example below shows the OnPaint method with a simple piece of code that displays "Hello World!" 20 dpi from the left and top edge of the screen.


protected override void OnPaint(PaintEventArgs e)
{
Graphics grfx = e.Graphics;
Brush foreColorBrush = new SolidBrush(Color.Black);
Font boldFont = new Font(Font.Name, 20, FontStyle.Bold);
grfx.DrawString("Hello World!",
boldFont,
foreColorBrush,
20 * grfx.DpiY / DESIGNPOINTSPERINCH,
20 * grfx.DpiY / DESIGNPOINTSPERINCH);
boldFont.Dispose();
foreColorBrush.Dispose();
grfx.Dispose();
}




Now try running the above code on a VGA and QVGA device, you'll see the position will be proportional to the screen size. This technique becomes very handy when the positioning is very important such as owner drawn lists etc.

No comments: