]> git.tdb.fi Git - libs/gltk.git/blob - source/image.cpp
Add Image widget
[libs/gltk.git] / source / image.cpp
1 /* $Id$
2
3 This file is part of libmspgltk
4 Copyright © 2007  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <msp/gl/bindable.h>
9 #include <msp/gl/immediate.h>
10 #include <msp/gl/matrix.h>
11 #include "image.h"
12 #include "part.h"
13
14 using namespace std;
15
16 namespace Msp {
17 namespace GLtk {
18
19 Image::Image(const Resources &r, const GL::Texture2D *i):
20         Widget(r),
21         image(i),
22         keep_aspect(true)
23 {
24         focusable = false;
25         update_style();
26 }
27
28 void Image::set_image(const GL::Texture2D *i)
29 {
30         image = i;
31 }
32
33 void Image::set_keep_aspect(bool ka)
34 {
35         keep_aspect = ka;
36 }
37
38 void Image::render_special(const Part &part) const
39 {
40         if(part.get_name()=="image")
41         {
42                 if(!image)
43                         return;
44
45                 const Alignment &align = part.get_alignment();
46                 Geometry rgeom = part.get_geometry();
47                 align.apply(rgeom, geom, part.get_margin());
48
49                 if(keep_aspect)
50                 {
51                         float aspect = static_cast<float>(image->get_width())/image->get_height();
52                         if(rgeom.w<rgeom.h*aspect)
53                         {
54                                 unsigned h = static_cast<unsigned>(rgeom.w/aspect);
55                                 rgeom.y += (rgeom.h-h)*align.y;
56                                 rgeom.h = h;
57                         }
58                         else
59                         {
60                                 unsigned w = static_cast<unsigned>(rgeom.h*aspect);
61                                 rgeom.x += (rgeom.w-w)*align.x;
62                                 rgeom.w = w;
63                         }
64                 }
65
66                 GL::Bind _bind_tex(image);
67                 GL::Immediate imm((GL::COLOR4_UBYTE, GL::TEXCOORD2, GL::VERTEX2));
68                 imm.color(1.0f, 1.0f, 1.0f);
69                 imm.begin(GL::QUADS);
70                 imm.texcoord(0.0, 0.0);
71                 imm.vertex(rgeom.x, rgeom.y);
72                 imm.texcoord(1.0, 0.0);
73                 imm.vertex(rgeom.x+rgeom.w, rgeom.y);
74                 imm.texcoord(1.0, 1.0);
75                 imm.vertex(rgeom.x+rgeom.w, rgeom.y+rgeom.h);
76                 imm.texcoord(0.0, 1.0);
77                 imm.vertex(rgeom.x, rgeom.y+rgeom.h);
78                 imm.end();
79         }
80 }
81
82 } // namespace GLtk
83 } // namespace Msp