Главная » Все файлы » Просмотр файлов из архивов » PDF-файлы » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

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

PDF-файл Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books), страница 96 Основы автоматизированного проектирования (ОАП) (17701): Книга - 3 семестрWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) - PDF, страница 96 (17701) - СтудИзба2018-01-10СтудИзба

Описание файла

Файл "Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007" внутри архива находится в папке "Symbian Books". PDF-файл из архива "Symbian Books", который расположен в категории "". Всё это находится в предмете "основы автоматизированного проектирования (оап)" из 3 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. .

Просмотр PDF-файла онлайн

Текст 96 страницы из PDF

Forgreater detail, see the example code.Table 17.2 Classes in Sample ApplicationClassDescriptionCExampleApplicationUsed by the UI framework to create aCExampleDocument object on applicationstart-upCExampleDocumentUsed by the UI framework to create aCExampleAppUiCExampleAppUiOn construction, creates aCExampleAppView and passes it a rectangleto work withThe rectangle is the client area: the area of thescreen available to the application fordrawing, which does not include the spacethat is available for the menu and applicationbands on the screen.

The CExampleAppUiclass also handles all user interfacecommands, notably ‘zoom out’ and ‘zoom in’.(Drawing.rss defines the menu options forimplementing these commands.)CExampleAppViewOn construction, splits the rectangle into fourquarters and creates a control,CExampleHelloControl, for each; in eachcase, the control is passed a rectangle to workwith (and for two of the controls, the ‘fullredraw’ parameter is set to false); the userinterface commands are passed to thesecontrolsCExampleHelloControlOn construction, creates a view,CExampleHelloView, and sets the text forthe view; also used for drawing on applicationstart-up and whenever the view changes:draws a border then calls its view’s drawfunctionCExampleHelloViewDraws ‘Hello World’ into the centre of therectangle, then draws a box around the textCExampleAppView and CExampleHelloControl are both controls, derived from CCoeControl.

Such controls are specific to screendevices and so cannot implement target-independent drawing code.The example separates out the target-independent drawing code intoa separate class, which is not a control: CExampleHelloView. It has534GRAPHICS FOR DISPLAYa drawing function that uses graphics context (CGraphicsContext)drawing functions and a graphics device map (MGraphicsDeviceMap)to access a graphics device’s scaling functions. We use the CExampleHelloView class to separate out size- and target-independent code intoan independent unit. This allows the size-independent code to be re-usedto draw to a printer.Nevertheless, CExampleHelloControl contains part of the size andtarget-independent code: it allocates the size and device-dependent fontwith which to do the drawing using an independent font specification.The role of each of the GDI classes (see Figure 17.15) is summarizedbelow.TZoomFactorCGraphicsDeviceCGraphicsContextMGraphicsDeviceMapTFontSpecCFontFigure 17.15 The application’s GDI classes• CGraphicsContext: the abstract base class created by a graphics device, CGraphicsDevice, which contains the main drawingfunctions.

It provides the ‘context’ in which you are drawing tothe associated device in the sense that it holds the pen and brushsettings (e.g., color, line styles), font settings (e.g., bold, underline,italic) and the clipping region (the visible drawing area). It dealswith pixels of device-dependent size and uses fonts with devicedependent size and representation. The sizes and fonts to be passedto CGraphicsContext functions, therefore, need to be convertedfrom size-independent units to size-dependent units.

This is doneby a class derived from MGraphicsDeviceMap: TZoomFactor orthe CGraphicsDevice. This class was described in more detail inChapter 16 and its handling of colors and bitmaps is described laterin this chapter.• MGraphicsDeviceMap: the abstract base class for both graphicdevices and zoom factors. It defines the size-dependent functions ina graphics device. These functions convert between pixels and twipsand perform font allocation and release.

Font allocation involvesfinding the font supported by the device which is the closest to adevice-independent font specification.DEVICE- AND SIZE-INDEPENDENT GRAPHICS535• CGraphicsDevice: the abstract base class for all graphics devices,which represents the medium being drawn to. It manufactures agraphics context suitable for drawing to itself (using CreateContext()), which takes into account the attributes of the device, suchas the size and display mode. It allocates (and releases) fonts suitablefor drawing to itself and converts between twips and pixels. Important graphic devices are CScreenDevice, CBitmapDevice andCPrinterDevice.

(Bitmap applications are discussed later in thechapter.)• TZoomFactor: defines a zoom factor and implements the MGraphicsDeviceMap interface. It allocates and releases device-dependent fonts and converts between twips and pixels. It facilitateszooming, because it allows the size of the graphic to becomeindependent of the target size. This class is recursive, because aTZoomFactor object can use an MGraphicsDeviceMap, whichcould be a TZoomFactor itself. This allows a zoom factor object tocontain another zoom factor object, multiplying the effect of the childzoom factor.

The top-level zoom factor uses a CGraphicsDevice(not another TZoomFactor).In the example application, the zoom factor uses the screen device.This is set up as follows in the control constructor:iZoomFactor.SetGraphicsDeviceMap(iCoeEnv->ScreenDevice());iZoomFactor is used to get the appropriate size and devicedependent font and size for drawing.Device-Independent DrawingIn this section, we study the device-independent drawing code inthe CExampleHelloView class and the small amount of deviceindependent code for allocating a font in the CExampleHelloControlclass. Then, we see how the drawing code is used by the CExampleHelloControl class.class CExampleHelloView : public CBase{public:// Construct/destructstatic CExampleHelloView* NewL();∼CExampleHelloView();// Settingsvoid SetTextL(const TDesC& aText);void SetFullRedraw(TBool aFullRedraw);536GRAPHICS FOR DISPLAY// Drawvoid DrawInRect(const MGraphicsDeviceMap& aMap, CGraphicsContext& aGc,const TRect& aDeviceRect, CFont* aFont) const;private:void ConstructL();private:HBufC* iText;TBool iFullRedraw;};Firstly, note that CExampleHelloView is derived from CBase, notfrom CCoeControl.

No CCoeControl-derived class can be deviceindependent, because controls are heavily tied to the screen.The drawing code is located in the DrawInRect() function, whichtakes a device map, a graphics context, and a rectangle within which todraw. DrawInRect() can be divided into two sections: it draws the textand a box around the text.Drawing a boxWe start by looking at the part that draws the box.

The following codedraws a box of a device-independent size. It is two pixels wide, dark grayon the ‘inside’ and black on the ‘outside’.void CExampleHelloView:: DrawInRect(const MGraphicsDeviceMap& aMap,CGraphicsContext& aGc, const TRect& aDeviceRect,CFont* aFont) const;{// Draw some text...// Draw a surrounding boxTSize boxInTwips(720,144); // 1/2" x 1/10" surrounding box// Converts twips to pixels, using iZoomFactor,// to get a box of 1/2" x 1/10"TSize boxInPixels;boxInPixels.iWidth = aMap.HorizontalTwipsToPixels(boxInTwips.iWidth);boxInPixels.iHeight = aMap.VerticalTwipsToPixels(boxInTwips.iHeight);TRect box(// Creates a TRect using boxInPixelsTPoint(aDeviceRect.Center().iX – boxInPixels.iWidth/2,aDeviceRect.Center().iY – boxInPixels.iHeight/2),boxInPixels);aGc.SetBrushStyle(CGraphicsContext::ENullBrush);aGc.SetClippingRect(aDeviceRect);aGc.SetPenColor(KRgbDarkGray);aGc.DrawRect(box);box.Grow(1,1);aGc.SetPenColor(KRgbBlack);aGc.DrawRect(box);// this makes the box 2 pixels thick}All graphics-context drawing functions are specified in pixels.

So,before we can draw the rectangle, we have to convert the size specifiedDEVICE- AND SIZE-INDEPENDENT GRAPHICS537in twips to a size in pixels. We use the twips-to-pixels functions of thegraphics device map. Remember that aMap ultimately uses the screendevice, which is how it can get the information about the number oftwips to a pixel.Now there is a problem: we cannot be sure that the box is containedentirely within aDeviceRect and we should not draw outside aDeviceRect. There is no guarantee, either on the screen or on anotherdevice, that drawing is clipped to aDeviceRect. Because we need thatguarantee, we set up a clipping rectangle explicitly.Even device-independent drawing code must take device realities intoaccount.We take device realities into account in a different way: although wecalculate the size of the surrounding rectangle beginning with twips, wedo the expansion explicitly in pixels.

Whatever display we draw thisrectangle to, we want it to consist of a two-pixel border: two lines spacedapart by a certain number of twips would overlap at small zoom statesand be spaced apart at large zoom states.Getting a fontFor this application, we have chosen to draw the message in 12-pointSwissA bold text. ‘12-point SwissA bold’ is a device-independent way ofspecifying a font.

We need to get a device-dependent font that meets thisspecification, taking into account the zoom state.Symbian OS supports fonts using the following classes (also seeFigure 17.15):• TFontSpec is a device-independent font specification, supporting aname, height and style (including italic, bold and superscript/subscriptattributes)• CFont is a device-dependent font accessed by CFont*; most CFontfunctions, such as AscentInPixels(), provide fast access to pixelsizes for any character or for a particular string.We could allocate (and release) the font along with the rest of the sizeand target-independent code in DrawInRect().

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