quick_recipes (779892), страница 38

Файл №779892 quick_recipes (Symbian Books) 38 страницаquick_recipes (779892) страница 382018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

The screen device is thenused to construct the graphics context within which the actual drawingcan be handled:User::LeaveIfError(iWsSession.Connect());iScreen=new(ELeave) CWsScreenDevice(iWsSession);User::LeaveIfError(iScreen->Construct());User::LeaveIfError(iScreen->CreateContext(iGc));Before any drawing can be done, a drawable window has to beconstructed and its area in the display needs to be defined:iWg=RWindowGroup(iWsSession);User::LeaveIfError(iWg.Construct((TUint32)&iWg, EFalse));iWg.SetOrdinalPosition(0,ECoeWinPriorityNormal);iWg.EnableReceiptOfFocus(EFalse);CApaWindowGroupName* wn=CApaWindowGroupName::NewLC(iWsSession);wn->SetHidden(ETrue);wn->SetWindowGroupName(iWg);CleanupStack::PopAndDestroy(wn);214SYMBIAN C++ RECIPESiMyWindow=RWindow(iWsSession);User::LeaveIfError(iMyWindow.Construct(iWg, (TUint32)&iMyWindow));TPixelsTwipsAndRotation SizeAndRotation;iScreen->GetDefaultScreenSizeAndRotation(SizeAndRotation);iScreenRect = TRect(TPoint(0,0),SizeAndRotation.iPixelSize);iMyWindow.Activate();iMyWindow.SetExtent(iScreenRect.iTl,iScreenRect.Size());iMyWindow.SetBackgroundColor(KRgbWhite);iMyWindow.SetOrdinalPosition(0,ECoeWinPriorityNormal);iMyWindow.SetNonFading(ETrue);iMyWindow.SetVisible(ETrue);In the Draw() function, the graphics context needs to be activatedbefore drawing and deactivated after drawing is finished:void CScreenDrawer::Draw(const TRect& aRect){iGc->Activate(iMyWindow);iMyWindow.Invalidate(aRect);iMyWindow.BeginRedraw();// Handle any drawing in here .

. .iMyWindow.EndRedraw();iGc->Deactivate();iWsSession.Flush();}If the application wants to get redraw events it needs to implementthe active object for monitoring redraw events generated by WSERV. Theredraw event request is handled by the RWsSession::RedrawReady()function.Discussion: The example given is really a minimal application, whichcould be used as a base for applications that do not need user interaction,but are shown according to some system events (for example, incomingcalls).To make the application more usable you need to also catch focusand key events and to make some kind of menu system to handle menucommands from the user. To catch key events, you could make anothersmall (1 pixel for example) window on top of this one, and construct itlike this:iWg=RWindowGroup(iWsSession);User::LeaveIfError(iWg.Construct((TUint32)&iWg, EFalse));GRAPHICS AND DRAWING215iWg.SetOrdinalPosition(1, ECoeWinPriorityNormal+1);iWg.EnableReceiptOfFocus(ETrue);CApaWindowGroupName* wn=CApaWindowGroupName::NewLC(iWsSession);wn->SetHidden(EFalse);wn->SetWindowGroupName(iWg);CleanupStack::PopAndDestroy(wn);A call to RWsSession::EventReady() will trigger your RunL()function, which should look like this:TWsEvent e;iWsSession.GetEvent(e);TInt type = e.Type();switch (type){case EEventKey:case EEventKeyUp:case EEventKeyDown:// react to key events herebreak;};For focus change monitoring, you could use the same base code, andjust add:User::LeaveIfError(iWg.EnableFocusChangeEvents());You could get the application that currently has focus with these linesof code:TInt wgid = iWsSession.GetFocusWindowGroup();CApaWindowGroupName* gn;gn = CApaWindowGroupName::NewLC(iWsSession, wgid);//gn->AppUid(), gives you the Uid of the application that is in focus.CleanupStack::PopAndDestroy(gn);What may go wrong when you do this: When you are not usingthe application framework, you will not be able to use the CEikonEnv::Static() function, simply because you don’t have the CONEenvironment constructed.

This can lead to problems when using someAPIs that require an environment variable to be set before they can beused, and for this reason you should be careful in selecting the APIsused.2164.5.3.5SYMBIAN C++ RECIPESDraw with Direct Screen AccessAmount of time required: 40 minutesLocation of example code: \Graphics_DSARequired library(s): gdi.lib, ws32.libRequired header file(s): gdi.h, w32std.hRequired platform security capability(s): NoneProblem: You need to improve the performance of your drawing routineby using direct screen access.Solution: To draw with drect screen access (DSA), you need to constructa CDirectScreenAccess object.

CDirectScreenAccess requiresa window server session, a drawable window and a screen deviceto be constructed first. Within the application framework you can getthe drawable window by calling the CCoeContainer::Window()function; for a screen device and window session you could use thefollowing code:CWsScreenDevice* screenDev= CEikonEnv::Static()->ScreenDevice();RWsSession winSession = CEikonEnv::Static()->WsSession();When working outside the application framework, you need to construct these objects as shown in Recipe 4.5.3.4.Discussion: The example given is a minimal application which could beused as a base for applications using DSA.A notable issue with the DSA API is that only one application at anygiven time can use it.

Thus to allow another application to use DSA API,you should release it by deleting the CDirectScreenAccess objectwhen your application does not have focus. When using DSA, WSERVallows an application to draw what it wants in a specified region. WSERVonly intervenes when an area of the screen being managed by DSA isobscured by another window for which it is responsible.Another notable issue that you should take into account is the framerate, which is device-dependent. Thus to optimize your drawing speedyou should not exceed the target device’s maximum frame rate.To minimize the drawing time, you should also consider using offscreen bitmaps, as shown in Recipe 4.5.3.1.

For more information aboutDSA and the use of off-screen bitmaps, see the recent Symbian Pressbook, Games on Symbian OS (developer.symbian.com/gamesbook) andconsult the Symbian Developer Library documentation. For more indepth information on the workings of WSERV and an introduction towriting GUI applications using the Symbian OS application framework,please see Symbian OS C++ for Mobile Phones, Volume 3.3D GRAPHICS USING OPENGL ES2174.6 3D Graphics Using OpenGL ESOpenGL ES is the embedded software industry’s standard of choice fordisplaying 3D graphics on the screen. It is a subset of the more widelyknown OpenGL standard, adapted to resource-constrained devices. Youcan find a link to the OpenGL ES specifications at the end of this set ofrecipes, in the Resources Section 4.6.6.There are not that many resources that cover OpenGL ES on Symbian OS, although you will find more information available in therecent Symbian Press book Games on Symbian OS: A Handbook onMobile Development (developer.symbian.com/gamesbook).

We can’texpect you to be particularly familiar with OpenGL ES. However, it isunrealistic to expect this small section to teach you everything there isto know about OpenGL ES, so we are going to teach you the basics ofOpenGL ES v1.0 on Symbian OS, and then point you to other resources,so you can expand on the basics to write interesting applications. Wewill explain how to scale back a full desktop OpenGL application sothat it can be ported to a smartphone. (If you do already know OpenGL,you need to realize that a lot of it will not be available in OpenGL ES.)OpenGL ES uses a C-based API and has little to do with Symbian OSC++, so most of the code samples in this section are not really going tolook like anything you have seen in this book.This section is probably the one where domain knowledge is the mostimportant.

Creating simple 3D objects is easy, but the amount of calculusrequired to create complex scenes can seem daunting to the novice.Open GL ES and Symbian OSSymbian has provided a software-based implementation of the OpenGLES 1.0 standard since Symbian OS v8.0a, and both S60 3rd Edition andUIQ 3 SDKs provide plug-ins to upgrade it to OpenGL ES 1.1.2 In fact, theS60 3rd Edition FP1 SDK includes the OpenGL ES 1.1 plug-in by default.Currently, Symbian smartphones with support for hardware-accelerated 3D graphics include the N82, N93 and N95 from Nokia, the P990,M600 and W950i from Sony Ericsson and the MOTORIZR Z8 fromMotorola.

Clearly, this opens the way to a level of quality in game graphics that has not been seen on mobile phones before. The Nokia devices allhave the PowerVR MBX graphics processor from Imagination Technologies, which you can read about at www.imgtec.com/PowerVR/Products/2You can find the plug-in for S60 3rd Edition development at: www.forum.nokia.com/info/sw.nokia.com/id/36331d44-414a-4b82-8b20-85f1183e7029/OpenGL ES 1 1 Plugin.html or by searching for ‘OpenGL ES 1.1 Plug-in’ from the main page of the Forum Nokiawebsite at www.forum.nokia.com.The OpenGL ES SDK for UIQ 3 is available from developer.uiq.com/devtools uiqsdk.html.218SYMBIAN C++ RECIPESGraphics/MBXLite/index.asp.

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

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

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

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