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

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

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

Each pixel takes 3 bytes, so for a5 megapixels image, the RAM required is 15 MB. You will run outof memory before the image is loaded if you do not increase themaximum heap value by using the EPOCHEAPSIZE keyword in yourMMP file, as Chapter 3, Section 3.13 described. For this reason (andGRAPHICS AND DRAWING203also because the screen is quite small and you can’t show the imagein full size), you could define a smaller target size when creatingthe image to be loaded, and it will be scaled to fit the size whenCImageDecoder loads it to the bitmap.4.5.2.2Draw Text to the ScreenAmount of time required: 15 minutesLocation of example code: \Graphics_ImagesRequired library(s): gdi.lib, ws32.lib, eikcore.lib, cone.libRequired header file(s): gdi.h, ws32std.h, eikenv.h,coetextdrawer.hRequired platform security capability(s): NoneProblem: You want to draw text onto the screen.Solution: Before you can draw any text onto the screen, you need toselect a font, set that font into use with the CWindowGc::UseFont()function and then call the text-drawing functions.

After you have finishedusing the font, you should call DiscardFont() to inform WSERV thatyou have finished using that particular font. When changing the font,you don’t need to call DiscardFont(), since calling UseFont() willautomatically discard the previously set font.To get a font you can use one of the different-sized system fontsaccessible through CEikonEnv::Static(), such as:• AnnotationFont()• TitleFont()• LegendFont()• SymbolFont()• DenseFont().On the S60 platform you can also use AknLayoutUtils::FontFromId() to get the normal system fonts (see the SDK documentation forAknLayoutUtils for further details).

As an example for text drawing, ifyou want to draw ‘Hello’ in the top left corner of your container with thetitle font, you can do it like this:_LIT(KTextBuffer, "Hello");gc.UseFont(CEikonEnv::Static()->TitleFont());gc.DrawText(KTextBuffer,TPoint(0,0));gc.DiscardFont();204SYMBIAN C++ RECIPESDiscussion: The text color is defined by the pen color settings.

The defaultcolor is black and you can change it with the SetPenColor() function.In addition, the rectangular area where the text is drawn is filled with thecurrent brush, and if you don’t want any fillings, you should set the brushstyle to Null before drawing any text to the container.With CWindowGc, there are two different variants of horizontal drawing one that renders text from a point, and another that renders text in abox.

Each is illustrated in Figure 4.5.1.void CWindowGc::DrawText(const TDesC& aBuf, const TRect& aBox, TIntaBaselineOffset, TTextAlign aHoriz=ELeft, TInt aLeftMrg=0)aBaselineOffset is the line on which the letters sit (for instance,below r, s, t and above the tail of q and y). aHoriz is the alignment(left, right, center). aLeftMrg is the text margin value (left margin forleft-aligned text, right margin for right-aligned text).Left end of textTPoint aPosition (x,y)Descending characterBaselineaBoxLeftendendofoftexttext(aligned(alignedleft)left)LeftaBaselineOffsetBaselineFigure 4.5.1 Rendering Text from a Coordinate Point (Top) and Rendering Text Within aBox (Bottom)If you want to draw vertical text, CWindowGc also defines two versionsof the DrawTextVertical() function.What may go wrong when you do this: For text drawing there are nodefault fonts set, thus you must set a font before attempting to drawany text.

Failing this will again generate a panic. Since the fonts arehandled by FBSERV, you should always release the font when you aredone with it, so the server can decrement the reference count for thefont and determine when it can be released from memory.GRAPHICS AND DRAWING205Tip: With the S60 platform you could also use AknLayoutUtils::FontFromId() to get the normal system fonts.Also note that CFont is a generic Symbian OS class that definesplenty of useful functions, as you can see in the system headerfile gdi.h. For example, you could check how many pixels thestring needs and then act accordingly when drawing the text into thecontrol’s screen.Characters that do not have a definition in the selected font willbe shown as empty rectangles.

For example, if you buy a normalBritish phone, and try displaying Chinese text on it, the phone mostlikely does not include any characters for Chinese text. The text wouldshow only a sequence of empty rectangles rather than the correctcharacters.4.5.2.3Load FontsAmount of time required: 15 minutesLocation of example code: \Graphics_ImagesRequired library(s): gdi.lib, ws32.lib, eikcore.libRequired header file(s): gdi.h, ws32std.h, eikenv.hRequired platform security capability(s): NoneProblem: You want to use fonts other than those supplied by the system,or you want to use the system fonts in different sizes to the default.Solution: If you want to use system fonts with special sizing or youwant to use other fonts included in the device, you need to first defineTFontSpec, which defines the name and size wanted for the font.You should then use it to load the font using the screen device’s GetNearestFontInTwips() function, which locates and loads the nearestmatch for the font requested.To know which fonts are installed on the device, you first need to getthe count for them by calling the NumTypefaces() function definedfor the screen device, and then you can get the TTypefaceSupportdefinition for each one by using TypefaceSupport() with a zerobased index number.

Then, to make the TFontSpec variable, use thename defined for the TTypefaceSupport and define the size required(100 is the normal size, anything smaller produces a smaller font size andanything bigger a bigger font size).TTypefaceSupport tfs;CEikonEnv::Static()->ScreenDevice()->TypefaceSupport(tfs, 0);TFontSpec spec(tfs.iTypeface.iName, 100);206SYMBIAN C++ RECIPESCFont* useFont;CEikonEnv::Static()->ScreenDevice()->GetNearestFontInTwips(useFont,spec);if (useFont){gc.UseFont(useFont);gc.DrawText(....);...CEikonEnv::Static()->ScreenDevice()->ReleaseFont(useFont);}Tip: Different devices may not have the same sets of fonts installedin them. In fact, sometimes even the same device model can havedifferent sets of fonts installed (for example, if it is for sale in a differentregion, or for a different language set).Relying on a device to have a specifically named font installedcould lead to problems when the code is executed on devices thatwere bought from other regions.4.5.2.4Draw Controls Inside Another ControlAmount of time required: 15 minutesLocation of example code: \Graphics_ImagesRequired library(s): cone.libRequired header file(s): coecntrl.hRequired platform security capability(s): NoneProblem: You want to have multiple controls inside your container.Solution: In general, controls that are located inside a control are notconstructed in their own window, but are actually using the window ofthe container control they are drawn in.Thus, the main change when constructing controls used inside othercontrols is to remove the code that constructs its own window.

Don’tcall CreateWindowL() in the control’s ConstructL() function, butinstead call SetContainerWindowL() with a reference to the container control.When using system controls defined in the SDK, most often theydon’t set the container window by themselves, but you actually needto call the SetContainerWindowL() function after constructing thecontrol. You can see this style used with CTextControl in the AboutContainer.cpp file:iTextControl = CTextControl::NewL(KtxLongText);iTextControl->SetContainerWindowL(*this);iTextControl->SetRect(SmallerRect);GRAPHICS AND DRAWING207When this code has executed, the control is constructed.

It has awindow to draw in and, after setting the rectangle where it lies inside thecontainer’s own window, it also knows where to draw.To get this control to refresh correctly, you also need to implement thefollowing two functions:TInt CAboutContainer::CountComponentControls() const{return 1;}CCoeControl* CAboutContainer::ComponentControl( TInt /*aIndex */) const{return iTextControl;}Discussion: When there is a redraw event for a CCoeControl-derivedclass, the system will first call the Draw() function of that container,and then call CountComponentControls() to determine how manycontrols inside the container need to be drawn. For each control to beredrawn, it calls ComponentControl() to retrieve a pointer to each ofthe controls inside the container, in turn.

The Draw() function is calledon each control, and then CountComponentControls() is called onthe control, in case there are controls residing within it.So the Draw() function is always called, and it is always calledfirst. This means that you could draw the background in it. And it alsomeans that in case your controls are filling the whole screen, then toavoid double drawing (and possible flickering) you probably should avoiddoing anything in the Draw() function.What may go wrong when you do this: In case your control is notshowing at all, check that you actually remembered to set the rectangle,since the rectangle area set for controls residing inside another controlis relative to the container control, and not relative to the screen.Check that you have specified it correctly (see the example code forthis recipe for a demonstration).In case your container draws once to the screen but then doesnot update, check that you are implementing CountComponentControls() and ComponentControl() correctly.Tip: Note that only controls that are put into the control stack (that is,those for which you called AddToStackL() in the application userinterface class) will receive key events.

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

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

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

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