Bada TutorialUI and Graphics
Transcript of Bada TutorialUI and Graphics
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 1bada 1.0.0b2
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved.
bada Tutorial: UI and Graphics
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 2
Contents (1/2)
• Essential Classes
• Relationships between Classes
• Overview
• Layers
– Coordinate System
– Example: Create a Form
• Controls and Containers
– Control Life-cycle
– Controls
• Example: Create a Bitmap Button
• Example: Create a List
– Containers
• Form-based Application
– Drawing Controls
– Showing Controls
– OverlayPanel
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 3
Contents (2/2)
• Event Handling
– Listeners
– Using IActionEventListener
– Using Other Listeners
– Custom Event
• XML UI Builder
• Sample Application: “BasicApp”
• FAQ
• Review
• Answers
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 4
Essential Classes
Feature Provided by
Provides the main window for an application. There can be only 1 frame. Frame
Provides the top level container with an indicator bar, soft key, and title bar. It is attached to a Frame.
Form
Provides a window that can be displayed on top of a Form or Frame. Popup
Provides containers to hold controls. Panel, ScrollPanel, OverlayPanel
Provides a window with pre-defined responses to prompt a user for input. MessageBox
Provides a generic button. Button
Provides a toggle. CheckButton
Provides input controls for single- or multiline text, date, and time. EditArea, EditField, EditDate,
EditTime
Provides a way to embed Flash Lite movies and applications. Flash
Provides a control to display text or images. Label
Provides different methods to display lists with text or images. List, IconList, CustomList,
ExpandableList, GroupedList,
SlidableList, SlidableGroupedList
Provides menus that contain menu items. OptionMenu, ContextMenu
Provides a progress bar to track how far along an operation is towards finishing. Progress
Provides a control to select a value inside of a range. Slider
Provides controls to select a date, time, or color. DatePicker, TimePicker, ColorPicker
Provides tools for custom animations. Animation, AnimationFrame
Provides utility function for handling touch events including multiple point touch. Touch
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 5
Relationships between Classes
Object
Control
Container
FormPanel
IFocusEventListener
IKeyEventListener
ITouchEventListener
IDragDropEventListener
Frame MessageBox Popup
Animation
Button
CheckButton
EditArea
List
…
…
Window
OverlayPanel ScrollPanel...
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 6
Overview
• The Ui and Ui::Controls namespaces contain classes and interfaces
to create graphical user interfaces.
• The Ui namespace contains common base classes for all controls
as well as interfaces for event handlers.
• The Ui::Controls namespace contains control classes, interfaces,
and other tools for display and interaction in the graphical user
interface.
• Key features include:
– Creating controls.
– Laying out controls.
– Handling control events.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 7
Layers
There are 3 basic layers in the window and control hierarchy:
– Frame: Contains Forms. An application can have only 1 frame.
– Forms: Contain containers and controls.
– Controls: These are containers and controls.
Frame
The top level window of an
application. There can only be
one per application.
Forms
Highest level container. Contains
containers and controls. There can be
multiple Forms per application. Each
Form has an indicator bar, soft key, and
title bar area.
Controls
Help to provide functionality
for an application. Controls can be added to containers, such as Forms or ScrollPanels.
Indicator barTitle bar
Soft key
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 8
Coordinate System
• You can get the bounds of the client area excluding the indicator, title, and tab using the GetClientAreaBounds() method.
• Frame dimensions are constant (for example: 480 x 800), but the
best practice is for applications to only use the available client area.
GetClientAreaBounds()
You can get the bounds of the
client area using this method.
GetBounds(),
GetWidth(), GetHeight()
You can get the bounds of the
control using these methods.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 9
Example: Create a Form
Create a form.
– Open \<BADA_SDK_HOME>\Examples\UIApplication\src\FormExample.cpp
1. Construct a Form: Form::Construct(formstyle)
2. Set soft key text in the form: Form::SetSoftkeyText(softkey, text)
3. Assign action IDs to the soft keys: Form::SetSoftkeyActionId(softkey, actionId)
4. Implement an IActionEventListener and an instance of the listener.
5. Register the listener with each soft key: Form::AddSoftkeyActionListener(softkey, listener)
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 10
Controls and Containers
• Controls are graphical user interface components that are displayed
inside of an application frame. Controls are divided into two general
classifications: “control” provides generic way to handle GUI
components but cannot contain others, and “container” can contain
other controls.
• Common control properties:
– Position and size
– Drawing logic
– Events:
• Key
• Touch
• Focus
• Common container properties:
– Derived from Control
– Parent–child relationships
class Control : public Object
{
Point GetPosition(void) const;
Dimension GetSize(void) const;
result Draw(void);
result Show(void);
void AddKeyEventListener(const
IKeyEventListener& listener);
void AddTouchEventListener(const
ITouchEventListener& listener);
void AddFocusEventListener(const
IFocusEventListener& listener);
// ...
};
class Container : public Control
{
virtual result AddControl(const Control& control);
virtual result RemoveControl(const Control& control);
};
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 11
Control Life-cycle (1/2)
You must create all containers and all controls on the heap memory.
– However, once the controls have been added to the container, and the container attached to the Frame, the application framework does all the
deleting when the application terminates.
void
Form1::SampleForm()
{
// all controls must be created on the heap memory
Button *pButton = new Button();
pButton->Construct(Rectangle(10, 100, 460, 60));
pButton->SetText(L”ButtonTest”);
pButton->SetActionId(10);
pButton->AddActionEventListener(*this);
AddControl(*pButton );
// do not delete pButton explicitly}
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 12
Control Life-cycle (2/2)
• Creation
– When a control gets initialized, OnInitializing() callback can be
overridden if application needs to do custom resource initialization.
• Deleting
– As a rule, do not explicitly delete controls that get added to a container,
the framework does that for you.
– You can use the RemoveControl() and RemoveAllControls()
methods to explicitly delete controls.
• Example: Create a single Form and add or remove controls such as buttons
at run-time depending on UI context, to preserve memory.
– You must explicitly delete controls which do not get added to the
container.
• MessageBox, Popup, ContextMenu and OptionMenu controls do not get
added to a container, so you have to explicitly delete them.
– When a control is getting deleted, OnTerminating() callback can be
overridden if application needs to do custom clean-up.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 13
Controls (1/5)
• Available GUI controls range from basic buttons to more advanced
controls, such as the time picker and animation controls.
• All controls are displayed in the graphical user interface. That is,
there are no controls that cannot be displayed, such as database
controls, data binding controls, providers, controllers, or adapters.
• Available GUI controls are shown below. Container controls are
marked with an asterisk (*). Controls that are containers due to
implementation reasons but do not allow the user to add more
controls to them are marked with a double asterisk (**).
GUI controls
Animation EditArea IconList Panel* Tab
Button EditDate Keypad** Popup* TimePicker**
CheckButton EditField Label Progress
ColorPicker EditTime List ScrollPanel*
ContextMenu** ExpandableList MessageBox** SlidableGroupedList
CustomList Flash OptionMenu** SlidableList
DatePicker** GroupedList OverlayPanel* Slider
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 14
Controls (2/5)
• Buttons can vary in size and use text or images.
• The CheckButton displays the user selection, either selected or
cleared and is often used in groups.
• The EditArea is for multiline input, while the EditField is for
single line input.
• List controls display the user selection in the form of a list of items.
• The IconList uses images (bitmaps) as icon files.
Buttons CheckButton EditArea/EditField IconListList
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 15
Controls (3/5)
• The CustomList contains items that consist of multiple elements
and have various item height.
• The ExpandableList presents items with a hierarchy.
• The GroupedList groups similar items together.
• The SlidableList and SlidableGroupedList are similar to
CustomList and GroupedList but load items in memory on
demand to save memory resources.
ExpandableList GroupedListCustomList
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 16
Controls (4/5)
• The OptionMenu presents a list of choices.
• The ContextMenu presents a list of context-sensitive options.
• The Popup and MessageBox display messages to people or prompt
people for input. Where MessageBox is simpler and easier, Popup
offers the versatility to embed other controls.
OptionMenu ContextMenu Popup MessageBox
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 17
Controls (5/5)
• There are many other controls
available in bada for a variety of
tasks.
• Adobe Flash developers should take special note of the Flash control
that allows you to embed Flash Lite
movies.
Progress
ColorPicker
DatePicker TimePicker
Keypad
TabSlider
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 18
Example: Create a Bitmap Button
Create a button using an image and a button using text, and add them to a form.
– Open \<BADA_SDK_HOME>\Examples\UIApplication\src\ButtonExample.cpp
1. Construct two buttons: Button::Construct(rectangle, “”)
2. Set an image on the first Button: Button::SetNormalBitmap(position, bitmap)
3. Set text on the second Button: Button::SetText(“Buy”)
4. Assign unique action IDs for each Button: Button::SetActionId(actionId)
5. Implement an IActionEventListener and create an instance.
6. Register the listener with each Button: Button::AddActionEventListener(listener)
7. Add the Buttons to the form:Form::AddControl(button)
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 19
Example: Create a List
Create and populate a list.
– Open \<BADA_SDK_HOME>\Examples
\UIApplication\src\ListExample.cpp
1. Construct a List:
List::Construct(rectangle, style, itemFormat,
row1Height, row2Height, column1Width, column2Width)
2. Populate the list: List::AddItem(text1, text2, bitmap1, bitmap2)
3. Implement an IItemEventListener and create an instance.
4. Add the listener to the list: List::AddItemEventListener(listener)
5. Add the list to a form: Form::AddControl(list)
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 20
Containers (1/2)
• Container is the base class for all containers.
• There are two categories of containers:
– General containers like Form and Panel.
– Containers used for special purposes, such as OverlayPanel,
ContextMenu and OptionMenu.
Containers Description
Frame Holds the main window and usually contains multiple Forms.
Form Occupies the full screen and includes an indicator bar, title bar, and soft keys.
ContextMenu
Displays a menu panel with menu items. OptionMenu
MessageBox Displays an alert window with a pre-defined set of options.
OverlayPanel Displays a panel container with a canvas in which you can draw a camera preview or display video.
Panel
Displays a panel container that other controls can be embedded in. ScrollPanel
Popup Displays a partial-screen window that can contain other controls.
DatePicker Displays a special window for editing date.
TimePicker Displays a special window for editing time.
Keypad Displays a full screen keypad.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 21
Containers (2/2)
Base::Object
Ui::Control
Ui::Container
Ui::Controls::Form Ui::Controls::Panel Ui::Window
Ui::Controls::OverlayPanel Ui::Controls::ScrollPanel
Ui::Controls::ContextMenu Ui::Controls::Frame Ui::Controls::MessageBox Ui::Controls::OptionMenu Ui::Controls::Popup Ui::Controls::TimePickerUi::Controls::DatePicker
• Panel is the most general control container. Panel can be used to
provide custom backgrounds for a group of controls.
• Window is inherited from Container and, thus, all its descendants
can contain other controls. However, many of Windows’s
descendants are designed for special purposes and are not general
containers.
• Note: When a container is destroyed, it deletes all child controls. Do not explicitly
delete child controls yourself. If you do delete them, the framework tries to delete
them again when the parent container is destroyed, causing unhandled exceptions.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 22
Form-based Application
• A Form is a typical unit in the flow of a UI application.
• Frame::SetCurrentForm(Form*) is used to make one form the
active form.
• You can utilize control’s name to easily identify forms.
– Use the Control::SetName() method to set a name.
– Get the application pointer using the Application::GetInstance()
method.
– Use the Control::GetControl() method to get the pointer to a
form by name.void
Form1::CreateForm1()
{
Form *pForm1 = new Form();
pForm1->Construct(FORM_STYLE_NORMAL);
pForm1->SetName(L"Form1");
}
void
Form2::OnActionPerformed(/* …*/ int actionId)
{
switch(actionId) {
case 0: {
Application *pApp = Application::GetInstance();
Frame *pFrame = pApp->GetAppFrame()->GetFrame();
Form *pForm1 = (Form *)pFrame->GetControl(“Form1”);
pFrame->SetCurrentForm(*pForm1);
pForm1->RequestRedraw();
}
…
}
}
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 23
Drawing Controls (1/2)
• Control::Draw() method
– Draws the control to the window canvas.
• Control::Show() method
– Causes the contents of the canvas to be actually copied to displayable
frame buffer.
• Control::RequestRedraw() method
– Request an asynchronous event that invokes the Draw() and Show()
methods.
– RequestRedraw() posts an event in the event queue and returns
immediately, so it is recommended to use this method in various
callback methods to trigger screen update.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 24
Drawing Controls (2/2)
• Container::OnDraw() is called when the system or another
container sends a request to paint the application's container.
• If you want to do custom drawing, you have to do it inside the OnDraw() callback.
• Make sure that the GetCavasN() method is used within the
OnDraw() implementation to retrieve the canvas the container is
using, otherwise the default Draw() function of the container will
overwrite the custom drawing.
result
MyForm::OnDraw(void)
{
result r = E_SUCCESS;
Canvas* pCanvas = GetCanvasN();
if (pCanvas) {
// add your drawing code here
}
if (pCanvas)
delete pCanvas;
// Do not call Show(). It will be called automatically after OnDraw() callback.
return r;
}
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 25
Showing Controls
• You can change the show state of a control using the Control::SetShowState(bool state) method.
• Changing the show state does not trigger the control to be displayed. To display the control, you must call the Show() method.
• Some controls automatically change their show state to false due
to their internal logic. For example, tapping an area outside a ContextMenu causes the show state to be changed to false.
(This applies to ContextMenu, OptionMenu, MessageBox, Popup
and Keypad.)// How to create an OptionMenu
void
SampleForm::CreateOptionMenu(void)
{
// Create a ContextMenu
__pOptionMenu = new OptionMenu();
__pOptionMenu->Construct();
__pOptionMenu->AddItem("Item1", ID_OPTIONMENU_ITEM1);
__pOptionMenu->AddItem("Item2", ID_OPTIONMENU_ITEM2);
// Display the OptionMenu on the display
__pOptionMenu->Show();
}
// How to show or hide an OptionMenu
void
SampleForm::ShowOptionMenu(bool show)
{
// Change to show state
__pOptionMenu->SetShowState(show);
// Call the control’s Show() method
if (show == true)
__pOptionMenu->Show();
// Call the container’s Show() method
else
Show();
}
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 26
OverlayPanel (1/3)
• OverlayPanel is a special type of panel which is used to specify a
region where the developer can playback video or show camera
preview.
• It is called an overlay because it is possible to overlay other graphics
and controls on top of the panel, as seen below.
• OverlayPanel consists of two layers of the same size: the
foreground panel and background buffer, which supports H/W
accelerated rendering.Foreground Panel
Input Buffer
Masking color
Background Buffer
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 27
OverlayPanel (2/3)
Input buffer
Source width
Source height
Destination width
Destination is positioned in the center of the background buffer.
Background buffer
Destination height
The following attributes can be adjusted when pixels are copied from
the input buffer to the background buffer:
– Size of the destination rectangle
– Rotation and flip
– Aspect ratio (whether the original aspect ratio of the input buffer is
retained or not)
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 28
Sourcesize
Destinationsize
Backgroundbuffer size
Rotation Retainingaspect ratio
Result
OverlayPanel (3/3)
50x50 50x50 80x80
50x50 50x50 80x80
50x50 80x50 80x80
None
Rotate 90°
Rotate 180°
True
True
False
50x50 50x80 80x80 Flip horizontally
False
The following table shows the different combinations of attributes:
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 29
Event Handling
• You must define listeners for controls in order to handle events.
• All controls can have drag and drop, focus, key, and touch listeners.
• Controls also have other listeners depending on their specific needs.
List
Key
Touch
Focus
Item
Button
Key
Touch
Focus
Action
Class
Event
Listener
listener call flow
Select by
touching
Click by
touching
Drag and Drop
Drag and Drop
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 30
Listeners
• All controls share some common listeners, but each control has
listeners that it specifically needs.
• Some listeners, such as IActionEventListener, are shared by
many controls. Others, such as IFlashEventListener, are
specific to only 1 control.
• Avoid using synchronous blocking calls in the event handler
implementations.
UI listeners
IActionEventListener IExpandableItemEventListener ISlidableGroupedListEventListener
IAdjustmentEventListener IFlashEventListener ISlidableListEventListener
IAnimationEventListener IFocusEventListener ITextEventListener
IColorChangeEventListener IGroupedItemEventListener ITimeChangeEventListener
ICustomItemEventListener IItemEventListener ITouchEventListener
IDateChangeEventListener IKeyEventListener IWindowEventListener
IDragDropEventListener IOrientationEventListener
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 31
Using IActionEventListener
• The IActionEventListener is an example of a listener that is
shared by many controls. It is used by:
– Button
– CheckButton
– ContextMenu
– OptionMenu
– Tab
• You must set action IDs inside of the above controls to receive them back in the OnActionPerformed() event handler. This allows
you to track actions and uniquely determine which control’s
associated functionality you need to run.
• By using unique action IDs, you only need a single IActionEventListener to handle events inside of an application.
IActionEventListener
actionId:
(1) Do X()
(25) Do Y()
(39) Do Z()
...
(N) Do N()
Button: actionId = 1
CheckButton: actionId = 25
Menu item 4: actionId = 39
Tab item 3: actionId = N
...
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 32
Using Other Listeners
• While many other listeners are shared between different controls,
not all listeners implement a unique ID to track which control was
responsible for an event.
• You can still track which control was responsible for an event as all
event handlers contain a calling control reference in their signatures:
– const Osp::Ui::Control &source
• The exception to this is IWindowEventListener. Instead of a
calling control reference, it contains a reference to the calling Osp::Ui::Window.
IActionEventListener
Control &source:
(Button1) Do X()
(CheckButton25) Do Y()
(MenuItem43) Do Z()
...
(ControlN) Do N()
Button1
CheckButton25
MenuItem43
ControlN
...
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 33
Custom Event
You can create custom events using Control::SendUserEvent().
– It is recommended to use this for inter-form communication (preferred over using
global variables to share data).
– It can also be used for inter-thread communication. UI handling should be done
in the main application thread. If the application spawns a thread, calling the SendUserEvent() method in that thread will cause a thread context change,
and the OnUserEventReceived() callback will be called in the main
application context.
RequestId reqIdCreatePopup = 10;
void
Form1::OnUserEventReceived(RequestId reqId,
IList *pArgs)
{
if (reqId == reqIdCreatePopup) {
// Do CreatePopup() action here
}
}
RequestId reqIdCreatePopup = 10;
void
Form2::OnActionPerformed(/* … */, int actionId)
{
switch(actionId) {
case 10: {
Application *pApp = Application::GetInstance();
Frame *pFrame = pApp->GetAppFrame()->GetFrame();
Form* pForm1 = pFrame->GetControl(“Form1”);pControl->SendUserEvent(reqIdCreatePopup, null);
}
…
}
}
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 34
XML UI Builder
You can utilize UI Builder which is part of the SDK, to design a form and
populate it with various controls.
1. Use UI Builder to design and layout contents of a form. An XML file is
generated.
2. Create a form using Form::Construct(L”<filename>”);
3. Use Control::GetControl() to get a pointer to the control you
want to use.
pForm->Construct(L”IDF_FORM”); // XML filename is IDF_FORM.xml
// All the controls are already added to the form at this point.
// There is no need to do pForm->AddControl(…).
// Add listeners
pForm->AddSoftkeyActionListener(SOFTKEY_0, *this);
pForm->AddOrientationEventListener(*this);
// To access a control within the form, use its ID defined in the UI Builder
// to get a pointer to it. This information can only be gotten from the Frame.
Button *pButton = (Button *)pForm->GetControl(“IDC_BUTTON”);
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 35
Sample Application: “BasicApp”
• Open \<BADA_SDK_HOME>\Samples\BasicApp\src.
• BasicApp shows:
– How to develop a UI application.
– How to create forms. You can see how to:
• Create a form with code, or with XML
• Create a button for a form.
• Add a listener to a button.
• Handle orientation
• Handle custom drawing
• A reference implementation for managing multiple forms
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 36
FAQ
• Who is responsible for deleting UI controls?
– You must create all Forms and all controls on the heap. However, once
the controls have been added to the Form (or container), and the Form
attached to the Frame, the application framework does all the deleting
when the application terminates.
• What is the difference between a Form and a Panel?
– Both are containers. That is, they can contain controls, such as Buttons and Lists.
– Only a Form can be added to a Frame window.
– A Form can have a title bar, indicator bar, and soft keys.
– A Panel is a general control container, and must be added to another
container, such as a Form.
• Is the List item format fixed?
– Yes. There are 11 pre-defined formats in Osp::Ui::Controls::ListItemFormat.
– For custom item formats, use a CustomList control.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 37
Review
1. Which is a superset of which? Container or Control?
2. Name the event types that are common to all controls.
3. Name the 3 basic layers.
4. What control would you use to play a video in?
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 38
Answers
1. Neither is a superset. Container inherits from Control and
contains methods that Control does not contain. Trick question.
2. Drag and drop, key, focus, touch.
3. Frame, Form, and Control.
4. OverlayPanel.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 39
Graphics
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 40
Contents (1/2)
• Essential Classes
• Relationships between Classes
• Overview
• Color
• BufferInfo
• Bitmap
– Example: Create a Bitmap
– Example: Stretch a Bitmap
• Shapes
– Example: Draw a Rectangle
– Example: Draw Text
• Canvas
• EnrichedText
– Example: Draw an EnrichedText
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 41
Contents (2/2)
• OpenGL®
– EGL
– OpenGL® ES
– Open GL® ES Versions and Download
– Sample Application: “GlesCube”
– Sample Application: “GlesCube11”
– Sample Application: “GlesCube11 – Pixmap”
• FAQ
• Review
• Answers
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 42
Feature Provided by
Provides an ordered pair to represent a coordinate on a 2D Cartesian plane. Point
Provides an ordered pair to represent a height and width measurement. Dimension
Provides a rectangle object for drawing with. Rectangle
Provides methods to store and manipulate a 32-bit color. Color
Provides font information and attributes. Font
Provides a spatially arranged array of pixel data along with attributes. Color bit-depth can vary
up to a maximum of 32 bits.
Bitmap
Provides a surface to draw on or render graphics or video on. Canvas
Provides methods to draw text with various fonts of different font face, style and size. EnrichedText
Provides methods to store the characteristics of text elements. TextElement
Provides additional information about the canvas. BufferInfo
Essential Classes
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 43
Relationships between Classes
Font Canvas Bitmap
Dimension PointRectangle
EnrichedText
TextElement
BufferInfo
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 44
Overview
• The Graphics namespace contains classes and interfaces that
provide 2D/3D graphics, text, and imaging features.
• Key features include:
– Drawing basics:
• Point, arc, ellipse, rectangle, polygon, text, and bitmap
• Colors, fills, and line styles
– Vector fonts
– Bitmaps with alpha
– OpenGL®
• EGL
• OpenGL® ES 1.1
• OpenGL® ES 2.0
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 45
Color
• bada uses 32-bit ARGB color by default, and automatically down-
samples for devices with lower color depth. Each channel occupies
8 bits for a range of 0~255 (0x00~0xFF).
• The following color-wheels show 24-bit color (16,777,216 colors)
fading to black and white.
Blue
(0, 0, 255)
Red
(255, 0, 0)
Lime
(0, 255, 0)
Cyan
(0, 255, 255)
Yellow
(255, 255, 0)
Magenta
(255, 0, 255)
White
(255, 255, 255)
Black
(0, 0, 0)
Blue
(0, 0, 255)
Green
(0, 128, 0)
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 46
BufferInfo
BufferInfo holds buffer information for canvases and bitmaps.
Attribute Description
bitsPerPixel Buffer bits per pixel
pixelFormat Buffer color format
pPixels Buffer starting pointer
pitch Length of buffer scan-line in bytes
width Width of buffer's logical dimensions in pixels
height Height of buffer's logical dimensions in pixels
Heig
ht o
f pare
nt b
uffe
rWidth
Height
Pixels
Pitch
(bytes)
Width of parent buffer Pixel format Description
PIXEL_FORMAT_RGB565 Pixel format is RGB565
PIXEL_FORMAT_ARGB8888 Pixel format is ARGB8888
PIXEL_FORMAT_R8G8B8A8Pixel format is R8G8B8A8 (byte
ordering)
PIXEL_FORMAT_YCBCr_420_PLAN
AR
8-bit Y-plane followed by 8-bit 2x2
sub-sampled U- and V-planes
PIXEL_FORMAT_JPEG JPEG-encoded formats
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 47
Bitmap (1/2)
• Bitmaps represent image data in terms of pixels. Each pixel is
represented with a fixed number of bits.
• Supported bitmap formats:
– RGB565
• Each pixel contains 16 bits of color information.
– ARGB8888
• Each pixel contains 32 bits of color information (24 RGB bits + 8 alpha bits).
• Alpha is supported, so images with transparency attributes can be displayed.
– R8G8B8A8
• Similar format as ARGB8888, except for the color component order.
• Used only for OpenGL® ES texture.
Bitmap format Description
BITMAP_PIXEL_FORMAT_RGB565 Pixel format is RGB565
BITMAP_PIXEL_FORMAT_ARGB8888 Pixel format is ARGB8888
BITMAP_PIXEL_FORMAT_R8G8B8A8 Pixel format is R8G8B8A8 (byte ordering)
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 48
• Bitmaps can be constructed from several sources:
• You can manipulate bitmaps:
– You can scale a bitmap to a different height and width.
– You can merge part or all of a bitmap onto a bitmap, and specify where
the bitmap data is placed on the target bitmap.
• You can directly read and write in bitmaps using locks:
– Inside a Bitmap::Lock() and Bitmap::Unlock() code block, you
can use BufferInfo to directly read and write pixel data. Ensure that
you call Bitmap::Unlock()after you are finished so that you release
the lock.
Source Description
Memory From a memory buffer that contains raw data
Canvas From a rectangular area on a canvas
Screen From a rectangular area on the screen
Bitmap From a rectangular area in a bitmap
Bitmap (2/2)
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 49
Example: Create a Bitmap
Draw a simple house and create a bitmap from the canvas. – Open \<BADA_SDK_HOME>\Examples\UIApplication\src
\GraphicsExample.cpp, CreateBitmapN()
1. Construct and clear a canvas: Canvas::Construct()Canvas::Clear()
2. Create the 4 vertices of the polygon as points: Point(20, 20)Point(80, 20)Point(90, 40)Point(10, 40)
3. Add the points to an IList.
4. Draw a filled polygon with the list of points:Canvas::FillPolygon(COLOR_BLUE, points)
5. Draw a filled rectangle: Canvas::FillRectangle(COLOR_RED, rectangle)
6. Show the canvas to the display: Canvas::Show()
7. Create a bitmap from the portion of the canvas with the image: Bitmap::Construct(canvas, Rectangle(10, 20, 80, 60))
(20, 20) (80, 20)
(90, 40)(10, 40)
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 50
Example: Stretch a Bitmap
Get a bitmap and stretch it onto a rectangle.
(Use the bitmap from the previous example.)
– Open \<BADA_SDK_HOME>\Examples\UIApplication
\src\GraphicsExample.cpp, DrawBitmap()
1. Construct and clear a canvas: Canvas::Construct()
Canvas::Clear()
2. Create rectangle for the bitmap: Rectangle(10, 10, 300, 300)
3. Get the bitmap from the previous example: CreateBitmapN()
4. Display the bitmap: Canvas::DrawBitmap(rectangle, bitmap)
5. Show the canvas to the display:Canvas::Show()
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 51
Shapes (1/3)
The following data structures are used in drawing shapes:
– Point
– Dimension
– Rectangle
Point
(x,y)
width
height
Dimension
(x, y)height
width
Rectangle
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 52
Shapes (2/3)
• Rectangle is used on canvases with bitmaps to draw shapes or
simply to define areas.
• The two most important parts of a rectangle are its upper left corner,
and its dimensions. These define its size and location.
• The rectangle’s position can be set either with a set of X and Y coordinates, or with a Point (an X and Y ordered pair).
• Similarly, the rectangle’s size can be set with a height and width, or with a Dimension (an X and Y ordered pair).
Rectangle
Top left corner
Height
Width
Bottom right corner
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 53
Shapes (3/3)
• All common shapes are relegated to being drawn using a Canvas.
• Some of the shapes that you can draw using a canvas include:
• While text is not a shape in the same sense as the other shapes,
drawing text onto a canvas is done the same way.
Arc Polygon Round rectangle
Ellipse Polyline Text
Line Rectangle Triangle
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 54
Example: Draw a Rectangle
Draw a 100x100 rectangle at (50,50) in red with no fill.
– Open \<BADA_SDK_HOME>\Examples\UIApplication
\src\GraphicsExample.cpp, DrawRectangle()
1. Construct a canvas: Canvas::Construct()
2. Clear the canvas: Canvas::Clear()
3. Set the line color to red: Canvas::SetForegroundColor()
4. Draw a rectangle onto the canvas: Canvas::DrawRectangle()
5. Show the canvas to the display: Canvas::Show()
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 55
Example: Draw Text
Print “Hello World” in italic, 32 pt.
– Open \<BADA_SDK_HOME>\Examples\UIApplication
\src\GraphicsExample.cpp, DrawText()
1. Construct a canvas.
2. Construct a font with style and size: Font::Construct(FONT_STYLE_ITALIC, 32)
3. Clear the canvas: Canvas::Clear()
4. Set the font to the canvas: Canvas::SetFont(font)
5. Draw “Hello World” onto the canvas: Canvas::DrawText(L”Hello World”)
6. Show the canvas to the display: Canvas::Show()
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 56
Canvas (1/3)
The following image illustrates the hierarchy and rectangular canvas area
where all graphics are rendered.
Form
Device screen
Canvas
Used to draw
primitives on
a canvas.
Frame buffer
Show
Frame
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 57
Canvas (2/3)
• A canvas contains settings that are used in drawing operations:
• Canvas:– Explicitly created using Canvas::Construct().
– Unknown to the window manager, so it can both overwrite other windows or be overwritten.
– Not recommended for general use, but is provided as a simple way to get a canvas.
• Window Canvas:– Retrieved from UI controls, for example,
Osp::UiControls::Frame::GetCanvasN().
– Managed by the system's window manager, so changes to the window are properly reflected in window canvases.
Setting attribute Description
Foreground color Drawing color for primitives
Background color Background color for clearing
Line style Line style (only Solid)
Line width Line width for primitives with a line style
Font Font used for text drawing
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 58
Canvas (3/3)
If a device supports less than 24-bit color, the color is automatically
down-sampled, and the alpha channel is unavailable.
PrimitiveLine style Fill style
CommentWidth Join end Solid Solid
Pixel
Line O Round O
Polyline O Round O
Triangle O Round O O
Rectangle O O O Normal or Rounded styles
Ellipse O O O
Arc O Round O O Arc, Chord, and Pie styles
Polygon O Round O O
Text OForeground color used for text drawing
Direction, Underline, and Strikeout
Bitmap
16-bit bitmap (with masking color)
32-bit bitmap (with alpha channel)
Normal, Scale, Partial, and Scale
drawing
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 59
EnrichedText (1/2)
• EnrichedText supports text with various styles, that is, font, color, and
layout.
• An EnrichedText consists of several TextElements, each of which
encapsulates the text attributes, such as the actual string and font style.
• You can manipulate the attributes of EnrichedText and TextElement.
Attributes of EnrichedText Description
Horizontal alignment Left, center, or right
Vertical alignment Top, middle, or bottom
Text wrapping style None, character wrap, or word wrap
Abbreviation Whether the drawn text is abbreviated in case the text size exceeds the
dimension of EnrichedText
Attributes of TextElement Description
Font size and style The font size and style: plain, bold or italic
Text color The foreground color of the text element
Background color The background color of the text element
Outline color The outline color of the text element
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 60
EnrichedText (2/2)
EnrichedText can be drawn using a canvas:
pEnrichedText->Construct(Dimension(width, height));
pCanvas->DrawText(Point(left, top), *pEnrichedText);
Point(left, top)
Canvas01234567890123
abcdefghijklmn\nABCDEFGHIJKTextElement
TextElement
EnrichedText
Size of EnrichedText• Left horizontal alignment• Abbreviation on
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 61
Example: Draw an EnrichedText
Draw an EnrichedText.
– Open \<BADA_SDK_HOME>\Examples\UIApplication
\src\GraphicsExample.cpp, DrawEnrichedText()
1. Create an EnrichedText:
EnrichedText::Construct(dimension)
2. Set the attributes of the EnrichedText:
EnrichedText::SetTextWrapStyle(TEXT_WRAP_CHARACTER_WRAP)
3. Create and add TextElements to the EnrichedText:
TextElement::Construct(L"01234567890123“)
EnrichedText::Add(TextElement&)
4. Set the attributes of the TextElement, that is, the color
and font:
TextElement::SetTextColor(Color::COLOR_BLUE);
TextElement::SetFont(font);
5. Construct and clear a canvas.
6. Display the EnrichedText:
Canvas::DrawText(Point(10, 10), *pEnrichedText)
7. Show the canvas on the display.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 62
EGL (1/2)
• EGL:
– Manages contexts and drawing surfaces for OpenGL® ES.
– Connects OpenGL® ES to the underlying window system and rendering APIs.
– Allows writing mostly-portable OpenGL® ES-based applications.
– Does not provide indirect (remote) rendering.
– Only binds one context to a rendering surface at a time.
– Supports single buffered rendering for pixmaps or back buffered rendering for windows and pbuffers.
– Has limited ability to mix native and OpenGL® ES rendering in the same window.
• Similarities:
– Conceptually the same as GLX (X windows) and WGL (MS windows).
– API is based on a simplified and restricted form of GLX.
– Similar data types:
• Displays
• Contexts
• Surfaces (drawables)
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 63
EGL (2/2)
• Mixing rendering:
– A pbuffer surface is an EGL Surface that is not associated with any
corresponding native object.
– Pbuffer surfaces do not support native rendering.
– Window surfaces support native rendering only after GL drawing is
finished and the result posted to the visible native window.
– Pixmap surfaces support native rendering if eglWaitGL() and
eglWaitNative() are used appropriately.
• The EGL version depends on the underlying mobile platform. You can use eglInitialize() and eglQueryString() at run-time
to determine which version of EGL is available.
• Details are available from the KhronosGroup website:
http://www.khronos.org/egl
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 64
OpenGL® ES
OpenGL® ES:
– Is the industry standard API for embedded graphics.
– Is the “official” OpenGL® subset, created with the blessing and
cooperation of the OpenGL® ARB.
– Eliminates redundancy and unneeded features to offer a significant size
reduction.
– Provides full functionality for 3D games.
– Is the most widely available cross-platform graphics API.
– Is royalty-free for the embedded industry.
Eliminate Redundancy
Eliminate Workstation Functionality
ARB
Feedback and Ratification
EmbeddedFocus
WorkstationFocus
Small Footprint
OpenGL ®Khronosgroup
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 65
OpenGL® ES Versions and Download
• OpenGL® ES 1.1 is for fixed function hardware and offers
acceleration, image quality and performance.
– Details are available from the KhronosGroup website:
http://www.khronos.org/opengles/1_X
• OpenGL® ES 2.0 enables fully programmable 3D graphics.
– Details are available from the KhronosGroup website:
http://www.khronos.org/opengles/2_X
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 66
Sample Application: “GlesCube” (1/2)
• Open \<BADA_SDK_HOME>\Samples\GlesCube\src.
– GlesCube.cpp
– Required headers and libraries:
• FGraphicsOpegngl2.h
• FGraphicsEgl
• FGraphicsOpengl
• GlesCube shows:
– Basic OpenGL® ES 2.0 usage.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 67
Sample Application: “GlesCube” (2/2)
The GlesCube application follows these basic steps using the specified
methods:
1. Initialize EGL.
• eglCreateWindowSurface()
2. Initialize GL.
• glCompileShader()
• glCreateProgram()
• glAttachShader()
• glLinkProgram()
• glUseProgram()
3. Start the timer to update the GL scene.
4. Draw.
• glDrawElements()
5. Update the screen.
• eglSwapBuffers()
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 68
Sample Application: “GlesCube11” (1/2)
• Open \<BADA_SDK_HOME>\Samples\GlesCube11\src.
– Related headers and libraries:
• FGraphicsOpegngl.h
• FGraphicsEgl
• FGraphicsOpengl
• GlesCube11shows:
– Basic OpenGL® ES 1.1 usage.
– Pbuffer usage.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 69
Sample Application: “GlesCube11” (2/2)
The GlesCube application follows these basic steps using the specified
methods:
1. Initialize EGL.
• eglCreateWindowSurface()
2. Initialize GL.
• eglCreatePbufferSurface()
• glGenTextures()
• glBindTexture()
• glTexImage2D()
• glFrustum()
3. Start the timer to update the GL scene.
4. Draw.
• glDrawElements()
5. Update the screen.
• eglSwapBuffers()
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 70
Sample Application: “GlesCube11 - Pixmap” (1/2)• Open \<BADA_SDK_HOME>\Samples\GlesCube11\src.
– Related headers and libraries:
• FGraphicsOpegngl.h
• FGraphicsEgl
• FGraphicsOpengl
• GlesCube11 shows:
– Basic OpenGL® ES 1.1 usage.
– Pixmap usage.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 71
Sample Application: “GlesCube11 - Pixmap” (2/2)The GlesCube application follows these basic steps using the specified
methods:
1. Initialize EGL.
• eglCreateWindowSurface()
2. Initialize GL.
• eglCreatePixmapSurface()
• glFrustum()
3. Start the timer to update the GL scene.
4. Draw.
• glDrawElements()
5. Update the screen.
• eglUpdateBufferOSP()
• Canvas::DrawBitmap()
• Canvas::Show()
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 72
FAQ
• How can I draw a JPG or PNG image?
– Use Media::Image to decode image files to Bitmap objects.
• Why are my drawings not being displayed?
– Make sure that you call Canvas::Show() to display the canvas.
• Why is a pixel color different from what I set?
– Colors are automatically down-sampled for devices with a lower color bit-depth. This can cause some loss of fidelity. For example, down-sampling 24-bit color to 16-bit color causes a loss of 8 bits in fidelity.
• Why am I getting an “Emulator failure. Could not initialize OGL entry point: glBindBuffer,” error and having other problems using OpenGL® ES 2.0?
– Your graphics hardware must support OpenGL® 2.1 to use OpenGL®ES 2.0, and support OpenGL® 1.5 to use OpenGL® ES 1.1.
• Can I use compressed textures for OpenGL® 1.1 or 2.0?
– Yes. The supported compressed texture formats are PVRTC and ETC. The bada SDK includes a command line tool to compress your texture files into PVRTC or ETC textures.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 73
Review
1. How big is the default bada color space?
2. What happens if a device only supports a lower color space than
the default bada color space?
3. Which type can be added to itself? Color, Dimension, Point,
Rectangle.
4. How do you display a PNG image?
5. What are the different kinds of canvases?
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 74
Answers
1. 32 bits (ARGB).
2. All colors are down-sampled.
3. Only Points can be added to other Points. Adding dimensions
cannot be done as an addition since that is ambiguous. Adding
rectangles is either nonsensical or ambiguous. Colors can be
added, but it requires mixing. There is no support in bada for
adding colors.
4. Decode it using the Media::Image class then draw it onto a
canvas.
5. Window and normal.
Copyright © 2010 Samsung Electronics Co., Ltd. All rights reserved. 75