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

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

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

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

If,later, the window needs to be redrawn, the window server uses thesecommands rather than sending a redraw to the client. This is particularlyuseful for transparent windows, as all of the windows that contribute tothe color of pixels in the relevant region can be drawn by the windowsever, without needing to involve the client. It can also be useful for anon-transparent window in the case where another window is drawn overthe first window and then disappears. The stored commands are usedto redraw the window immediately, rather than waiting for the client toperform a redraw.With redraw storing in operation, the window server can draw thewindow in many more situations without requiring a redraw from theclient.

Remember, though, that when the client actually wants the contentof its window to change, it has to tell the window server, by a call toInvalidate(), to request a redraw. Fortunately, this fits in with theway a client would normally update part of its window, as DrawNow()and DrawDeferred() both call Invalidate().However, clients that have more than one view need to take additionalactions when redraw storing is active. Consider the case where, whileone view is visible, the user performs some action that changes themodel of the application and then switches to another view.

Withoutredraw storing, the second view would have received a redraw event andso would have drawn itself to reflect the model changes. With redrawstoring in operation, the second view would not receive a redraw event inthis situation and thus it would continue to show the unchanged model.To avoid this problem, the client would need to call Invalidate() onall non-visible views, either when the model changes or when such aview comes to the foreground.When redraw storing is in operation for a window, the window serveralways tries to hold a set of commands that would allow it to draw thewindow. Thus, if anything happens that makes the stored commands outof date, the window server discards them and issues a full redraw toDEVICE- AND SIZE-INDEPENDENT GRAPHICS529the window so that it can create an updated list of stored commands.Operations that cause this to happen include:•••••calling Invalidate() on part or all of the windowperforming a redraw on part of the windowperforming some non-redraw drawing on the windowscrolling the windowchanging the window’s size.While redraw storing is in operation on a window, it is best thatapplications avoid using these operations; if they are used and thewindow behind is a transparent window, they are in danger of beingdrawn with the wrong content if the transparent window needs drawing.The window server is configured at boot time to use, or not use, redrawstoring.

If transparent windows are enabled, then redraw storing shouldalways be used. It can be turned on or off for a particular window (otherthan a transparent window) by calling:TInt RWindow::EnableRedrawStore(TBool aEnabled);In Symbian OS v9.1, redraw storing was extended to deal moreeffectively with the situation of a client performing a partial redraw.Before this change, a partial redraw by a client caused the window serverto throw away all the stored commands and then to force the client toperform a full redraw.

After the change, the commands corresponding tothe client’s partial redraw are simply added to the redraw store, alongwith the part of the window that they refer to. The window server cantherefore continue to draw the modified window content, using the storedcommands from the initial full redraw, together with those from any laterpartial redraws.In some circumstances, following a complex drawing sequence,the window server’s repeated execution of the stored instructionscan end up adversely affecting an application’s performance.

Youcan clear the stored sequence by executing an empty – or nearlyempty – BeginRedraw() - EndRedraw() sequence.17.9 Device- and Size-Independent GraphicsThis section discusses how to write graphics code that is independent ofthe size of the graphics and the device to be drawn to. First, we studythe writing of graphical applications – a topic that involves both sizeand device-independent drawing code. Then, we cover the subjects ofblitting, fonts and color as these subjects are heavily influenced by theneed for size- and device-independence.530GRAPHICS FOR DISPLAY• Size-independent drawing allows zooming of a graphic and is necessary when drawing to different targets, such as different-sized screens.• Target-independent drawing allows an application to draw to morethan one kind of device, such as a screen and a printer.• Device-independent graphical user interfaces requires not just onscreen drawing, but interaction as well.

CONE’s principles of pointerand key distribution, focus and dimming (see Chapter 18) can be usedfor any GUI. But the way that Uikon (and, particularly, a customizedlayer such as UIQ or S60) builds on CONE is optimized for a particulardevice and its targeted end-users. It turns out that the design of theGUI, as a whole, is heavily dependent on device characteristics.Printing is a capability that featured in earlier Symbian OS devices.Although it is not used in the current range of Symbian OS smartphones,it continues to be supported and is likely to be reintroduced in futureproducts.

Symbian OS has supported target-independent drawing fromthe start, so that all components can be written to print or draw toa screen.The Developer’s Quest for Device-independent CodeIt is not always worthwhile making your code target-independent. So,when should you make your drawing code device-independent and whendo you not need to? There are two extreme cases in which the answer isquite clear:• if your code is designed exclusively for a screen-based user interface,then it should not be target-independent (though you may wish tobuild in size independence)• If your code is designed primarily for printing, with a screen-baseduser interface for editing, then it should be device-independentAn application toolbar can be highly device-dependent, as can themenu and the dialogs (though some size independence may be useful fordialogs).

On the other hand, a text view intended for a word processorshould be device-independent; so too should a mapping program thatmight well be printer-oriented.This answer is only a starting point, however, and there are manyawkward, intermediate cases. You have to take the realities of the deviceinto account, even when writing the most device-independent code.The influence of target devices on your code is even greater when thedevices are relatively limited in CPU power and display resolution. Withhigh-resolution displays and near-infinite CPU power, you can rendereverything with no thought for rounding errors, scale, etc. With smallDEVICE- AND SIZE-INDEPENDENT GRAPHICS531displays, slower CPUs and no floating-point processor, you have to takemuch more care in both graphical design and programming.In a map application, zooming introduces considerations not only ofscale, but also of visibility.

In a high-level view of a map, you want tosee the coastline, a few major cities, big rivers and any borders. In azoomed-in view of a city, you want to see district names, undergroundtrain stations, public buildings, etc. In the high-level view, you wouldn’ttry to draw these details at small scale: you would omit them altogether.And this omission is device-dependent: you can include more minorfeatures in a printed view than in an on-screen view at the same zoomlevel, because most printers have higher resolution than a screen.There are plenty of other complications with maps, such as aligninglabels with features and transverse scaling of linear elements such asroads – and many other applications share these considerations. Fortunately, you do not usually edit maps on a handheld device, so there isn’tthe need for the very quick reformatting code that there is with wordprocessors. As a result, there may be better code sharing between printerand screen views.Size- and Target-independent Drawing for ApplicationsGraphical applications may need to support zooming and drawing to different targets: different screens, printers and different types of smartphone,with different screen sizes.The classes that support size-independence are the same for eachtarget: CGraphicsContext, MGraphicsDeviceMap, MGraphicsDevice and TZoomFactor.

These have to be implemented differentlyfor the different targets. They are part of the Graphics Device Interface(GDI). Drawing code in an application uses the functions and settings ofthe GDI classes.The example applicationThe example application in this chapter demonstrates how to implementzooming on a screen device. For screen devices, controls are used(derived from CCoeControl) to allow user interaction with the graphicand a GUI is used to display and provide an interface to the application.After going through the example code, we see how the size-independentcode may be re-used when drawing to a printer.You can download the example code for this application fromdeveloper.symbian.com/main/academy/press.

Figure 17.13 shows ascreenshot for the example application. The top-left and bottom-rightrectangles are used to illustrate the need to do a ‘full redraw’ rather thandrawing over the existing graphic, a point that we’ll come back to alittle later.The application structure is shown in Figure 17.14. In order to setthe size-independent drawing code in context, an overview of how the532GRAPHICS FOR DISPLAYFigure 17.13 The sample applicationMGraphicsDeviceMapCGraphicsDeviceCExampleHelloViewCGraphicsContextCExampleHelloControlCCoeEnv4TZoomFactorCCoeControlCExampleAppViewCEikAppUICExampleAppUiCEikDocumentCExampleDocumentCEikApplicationCExampleApplicationFigure 17.14 The structure of the sample applicationDEVICE- AND SIZE-INDEPENDENT GRAPHICS533example application classes work together is shown in Table 17.2.

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

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

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

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