ravi.joshi53's picture

How to create a button in OpenTK


I wanted to create a button in OpenTK which should have following features-

  1. It should change the color or texture whenever it has been clicked, so that the click event can be seen in UI
  2. It should have a label (text) written over it
  3. It should be auto resizable in length, whenever the length of label is more than it

These buttons are big enough in size (i.e. ~200*100 pixel )

How to develop it? Should I create a bitmap of the texture and then draw the label on it?

Any suggestions please...


Inline Images


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
the Fiddler's picture

Writing a complicated GUI in OpenGL is not the simplest of tasks. If it's just buttons and a few other GUI elements, then it's feasible, but for anything more complicated I would look into using a dedicated GUI toolkit, such as Windows.Forms, GTK#, Qt or something similar (you can use OpenTK with any of those.)

That aside, if it's just a few buttons, I would use System.Drawing.Graphics or QuickFont to prepare the labels and upload them as OpenGL textures. This is the simplest approach to render text; you can find a complete example here: TextRendering.cs.

The code basically comes down to this:

// Load text font
Font sans = new Font(FontFamily.GenericSansSerif, 24); // you can also load a custom font
// Create GDI+ Graphics object
var bmp = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var gfx = System.Drawing.Graphics.FromImage(bmp);
gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
// Render a text label
gfx.DrawString("Login", sans, Brushes.White, PointF.Empty);
var size = gfx.MeasureString(text, sans);
// You can now upload bmp to an OpenGL texture for rendering.
// Since text rendering with GDI+ is slow, you can try creating all
// labels & textures in the Load event and only rendering the textures
// in RenderFrame.
ravi.joshi53's picture


I think, it would be much simple if I can use color instead of texture in background of the button. Still I have two pending requirements-

  1. The button should be auto resizable in length. If the text is bigger than it, it should increase the length
  2. The button should change the color whenever clicked (To show that it has been clicked)

The example code which you suggested me to refer is creating a full window bitmap and then assigning a background color to it. However I wanted to have this background color in a specified area, which is basically the size of the button.

I will appreciate more if you can suggest a way with sample code.