Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 86

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 86 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 862018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 86)

A control needs both aConstructFromResourceL() and a ConstructL() if it is to beused both inside and outside a dialog. On entry to ConstructFromResourceL(), the passed resource reader is positioned at the start ofthe control’s data and the function consumes all available data for thecontrol.void CMyCustomControl::ConstructFromResourceL(TResourceReader &aReader){// Read the width and height from the resource file.TInt width = aReader.ReadInt16();TInt height = aReader.ReadInt16();TSize controlSize (width, height);SetSize(controlSize);ActivateL();}The default implementation of ConstructFromResourceL() isempty, so we do not need to implement it if our custom control has noassociated resource struct.We must, however, implement the dialog’s CreateCustomControlL() function in each dialog that contains one or more customcontrols and it must be capable of creating every custom control thatappears in the dialog.

The function is called from the system’s controlfactory whenever it is asked to construct a control of an unknown type. Itis unusual in that it returns an SEikControlInfo structure, defined ineikfctry.h as:struct SEikControlInfo480DIALOGS{CCoeControl* iControl;TInt iTrailerTextId;TInt iFlags;};In most circumstances, it is sufficient to set the iControl element topoint to the newly constructed control and set the remaining elements tozero, as in the following example:SEikControlInfo CMyCustomControlDialog::CreateCustomControlL(TInt aControlType ){SEikControlInfo controlInfo;controlInfo.iControl = NULL;controlInfo.iTrailerTextId = 0;controlInfo.iFlags = 0;switch (aControlType){case EMyCustomControl:controlInfo.iControl = new(ELeave) CMyCustomControl;break;default:break;}return controlInfo;}SummaryThis chapter has introduced and explained the basics of dialogs.

There aremany differences between developing dialogs on S60 and on UIQ. In S60,all dialogs are ultimately derived from CEikDialog. UIQ has deprecatedCEikDialog and replace it with two new classes: CQikSimpleDialogand CQikViewDialog.The chapter started by explaining what a dialog is and presentedsome examples of simple and complex dialogs. The dialog API was alsopresented and the differences between S60 and UIQ were explained. Weended the chapter by showing how to customize a dialog and givingsome basic examples of standard dialogs.17Graphics for DisplayIn the previous few chapters, we have begun to get familiar with the GUI,but we have got about as far as we can without a deeper understandingof Symbian OS graphics.

Although we saw some specific examplesof drawing to an application’s views in Chapter 15, most of the otherdrawing – for example, in menus, dialogs and standard controls – hasbeen done by the Uikon, UIQ or S60 frameworks.Now it is time to look at graphics in more detail. In this chapter, wecover the things you need to know for more sophisticated and effectiveon-screen drawing:• how to get graphics on screen• how to use the CGraphicsContext API• the model–view–controller (MVC) paradigm• how to update the screen without producing visible flicker• how to share the screen using windows (RWindow) and controls(CCoeControl)• the special effects supported by the Symbian OS graphics system• drawing-related features in the window server• size-independent drawing, including zooming• target-independent drawing and drawing to more than one outputdevice• device characteristics.In Chapter 18, we cover support for user interaction based on keyboardand pointer devices.48217.1GRAPHICS FOR DISPLAYDrawing BasicsGUIs present many more opportunities for displaying data than a consoleprogram.

Even in a program that does nothing more than display ‘HelloWorld’, you face these issues:• What font should you use?• What colors should you use for the foreground and background?• Where should you put the text?• Should you set the text off in some kind of border or frame?• How big is your screen and on how much of it do you draw the text?Whichever way you look at it, you have to make these decisions,so the part of your program that says ‘Hello world!’ is bigger than thecorresponding part of a text-mode program. Here is the Draw() functionof a typical graphical ‘Hello World’ program:void CHelloWorldAppView::Draw(const TRect& /*aRect*/) const{CWindowGc& gc = SystemGc();gc.Clear();TRect rect = Rect();rect.Shrink(10, 10);gc.DrawRect(rect);rect.Shrink(1, 1);const CFont* font = iEikonEnv->TitleFont();gc.UseFont(font);TInt baseline = rect.Height() / 2 + font->AscentInPixels() / 2;gc.DrawText(*iHelloWorld, rect, baseline, CGraphicsContext::ECenter);gc.DiscardFont();}That’s eleven lines of code, where one would have been enoughin a console-based program.

The good news, though, is that you canmake decisions you need and it is relatively easy to write the codeto implement whatever you decide. The example above illustrates theessentials of drawing:• draw your graphics to a control – CHelloWorldAppView is derivedfrom CCoeControl• use the CGraphicsContext API to draw the graphics.DRAWING BASICS483Figure 17.1 HelloWorld application screenControlsIn Chapter 15 we explained that all drawing is done to a control – arectangular area of screen that occupies all or part of a window. The baseclass for all controls is CCoeControl, which is defined by the CONEcomponent in Symbian OS.The screen in Figure 17.1 includes two windows: the application viewand the button bar.

The application view is a single control and thebutton bar comprises several controls: a container for the whole buttonbar, which is a compound control and component controls, including thefour buttons.This application already allows us to make some generalizations aboutcontrols:• for an application, a control is the basic unit of GUI interaction: acontrol can do any sensible combination of drawing, pointer handlingand key handling• a window is the basic unit of interaction for the system: controlsalways use all or part of a window• controls can be compound: that is, they can contain componentcontrols; a compound control is sometimes known as a container.Getting the Graphics ContextIn Symbian OS, all drawing is done through a graphics context.

TheCHelloWorldAppView::Draw() function uses SystemGc(), a function in CCoeControl, to get hold of a graphics context:CWindowGc& gc = SystemGc();484GRAPHICS FOR DISPLAYAll graphics-context classes are derived from CGraphicsContext.Each derived class – such as CWindowGc – is used to draw on a particulargraphics device (in our example, a window). It implements all thefunctionality specified by the base class and may also implement extrafunctionality appropriate for the device in question.

For example, we canclear the screen through the graphics context:gc.Clear();A ‘graphics context’ is a common notion in the world of computergraphics. Windows uses a ‘device context’; Java uses a Graphicsobject.Drawing a RectangleThe next three lines of code draw a rectangular border ten pixels in fromthe edge of the application view’s area on the screen:TRect rect = Rect();rect.Shrink(10, 10);gc.DrawRect(rect);CCoeControl::Rect() gives the coordinates of the rectangle occupied by the control from within which Rect() is called, in this case theapplication view. The coordinates are given relative to the window thatthe control uses.

The coordinates used by CWindowGc drawing functionsmust also be relative to the window, so this is convenient.Shrink() makes the rectangle 10 pixels smaller than the control’srectangle on every side – top, right, bottom and left. TRect containsmany utility functions like this.DrawRect() draws a rectangle using the default graphics contextsettings. These settings specify:• that the pen creates a black, one-pixel wide, solid line: this causes theboundary of rect to be drawn in black• that the brush is null, which means that the rectangle is not filled.You can rely on the default graphics context configuration being setup prior to your Draw() function.

Do not waste your time setting thingsthat are the default.Drawing the TextNow, we draw the text, centered in the rectangle. For good measure,we start by shrinking the rectangle by one pixel on each side, so thatDRAWING BASICS485we can afford to white it out without affecting the border we have justdrawn:rect.Shrink(1, 1);Then, we get a font from the UI environment:const CFont* font = iEikonEnv->TitleFont();This is our first encounter with a CFont*.

Later in this chapter, welook at how to get a font of a desired typeface and size, with bold or italicattributes, and so on. To avoid these issues right now, we use a title fontfrom the environment – it is the font used on the title bar of dialog boxes,and it is suitably bold and large.It is not enough just to have a pointer to the font; we must also tell thegraphics context to use it:gc.UseFont(font);This call to UseFont() sets the font for all subsequent text-drawingfunctions – until another UseFont() is issued or until DiscardFont()is called.Now we need to draw the text, centered in the rect rectangle:TInt baseline = rect.Height() / 2 + font->AscentInPixels() / 2;gc.DrawText(*iHelloWorld, rect, baseline, CGraphicsContext::ECenter);where iHelloWorld is a pointer to a descriptor containing the text tobe drawn.The DrawText() function conveniently both draws text – with thegraphics context’s pen and font settings – and clears the entire rectanglearea using the current brush settings.

Характеристики

Тип файла
PDF-файл
Размер
6,45 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6367
Авторов
на СтудИзбе
309
Средний доход
с одного платного файла
Обучение Подробнее