Главная » Все файлы » Просмотр файлов из архивов » 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), страница 97

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

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

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

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

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

However, DrawInRect() is not, and should not be, a leaving function as it is called from theDraw() function of the Hello control. However, font allocation could failand might leave. It is possible to get around this problem using a trap harness, but we do not do this as it is not good practice. It is also bad practiceto allocate resources while drawing, so it would make the code unsuitablefor large-scale use. Therefore we allocate and release fonts in CExample-538GRAPHICS FOR DISPLAYHelloControl::SetZoomAndDeviceDependentFontL().

This isan appropriate location for the font allocation as it is called both on classconstruction and as a result of zooming in and out: the size-dependent fontis expected to change when the user zooms in or out (and at no other time).void CExampleHelloControl::SetZoomAndDeviceDependentFontL(TInt aZoomFactor){// Set zoom factor...// Allocate a device dependent font for drawingiZoomFactor.ReleaseFont(iFont);iFont = NULL;_LIT(fontName, "SwissA");TFontSpec fontSpec(fontName,100);fontSpec.iFontStyle = TFontStyle(EPostureUpright, EStrokeWeightBold,EPrintPosNormal);User::LeaveIfError(iZoomFactor.GetNearestFontInTwips(iFont, fontSpec));}The key function here is GetNearestFontInTwips(), a memberfunction of MGraphicsDeviceMap.

You pass a TFontSpec to thisfunction and get back a pointer to a device-dependent font (a CFont*).The mapping from TFontSpec to CFont* is ultimately handled by agraphics device (though the font specification may be zoomed by a zoomfactor). Once you have a CFont*, you can only use it on the device thatallocated it – more precisely, you can only use it for drawing through agraphics context to the device that allocated it. This function usually findsa match but, in the unlikely case that it does not, it returns an error code:we propagate any error by calling User::LeaveIfError().Notice the need to release the font after use; when you no longer needa CFont*, you must ask the device to release it.

If you forget to release afont, the effect is the same as a memory leak: your program is panicked onexit from emulator debug builds. There is no error if ReleaseFont() iscalled when the font has not been allocated yet: the function just returns.Therefore it is safe to release the font at the start of the function. The lastfont allocated is released in the Hello control class destructor.The code allocates NULL to iFont because the function may leavebefore the font is allocated. In this case, the destructor would attempt torelease the font again, causing the application to crash.The font specification uses the TFontSpec class, defined by the GDIin gdi.h:class TFontSpec{public:IMPORT_C TFontSpec();IMPORT_C TFontSpec(const TDesC& aTypefaceName, TInt aHeight);IMPORT_C TBool operator==(const TFontSpec& aFontSpec) const;IMPORT_C void InternalizeL(RReadStream& aStream);DEVICE- AND SIZE-INDEPENDENT GRAPHICS539IMPORT_C void ExternalizeL(RWriteStream& aStream) const;public:TTypeface iTypeface;TInt iHeight;TFontStyle iFontStyle;};A font specification consists of a typeface, a height and a font style.The TTypeface class is also defined by the GDI.

It has several attributes,of which the most important is the name.When you use GetNearestFontInTwips(), the height is expectedto be in twips, though some devices support a GetNearestFontInPixels() function that allows the height to be specified in pixels.The font style covers posture (upright or italic), stroke weight (bold ornormal), and print position (normal, subscript or superscript).Other font attributes, such as underline and strikethrough, are not fontattributes at all – they are drawing effects and you apply them usingthe CGraphicsContext functions.TFontSpec has a constructor that we used for specifying a font in asingle statement.

It also has a default constructor and assignment operator.Finally, TFontSpec has ExternalizeL() and InternalizeL()functions. These are important: a rich text object, for instance, must beable to externalize a TFontSpec object when storing and internalize itwhen restoring. TFontSpec objects can be stored with a rich text object(i.e.

a document of some sort). They provide necessary information abouthow to display the document on a screen or printer. The TFontSpecclass comes into use whenever a rich text object is stored in or restoredfrom a file. TFontSpec is useful to any application that can display textin more than one size or to more than one target.Zooming and fontsBefore we move on, there is a problem associated with zooming text atvery low zoom factors. If this is not dealt with properly then the width oftext at low zoom factors does not scale in proportion to the height. Thisgives rise to the effect illustrated in Figure 17.16, where the text is toowide for the surrounding box.We may want to display the shape of words, sentences and paragraphseven when the font is too small to read.

This requirement applies to aprint preview and the Symbian OS rich text view, unlike our application,can properly handle and display fonts even smaller than a pixel. Not allsmartphone views have to support this. For many smartphones it is notactually an issue.540GRAPHICS FOR DISPLAYFigure 17.16 Text at a very low zoom factorWhen you get a CFont* from a TFontSpec, you convert from atwips size to a pixel size.

Pixels are not necessarily square but usually, asyou would expect, the height and width of a font scale proportionately.When text is displayed at smaller than a pixel this is not necessarily thecase because the smallest unit that a letter can be written in is a pixel, sospecial scaling support is needed.The way of getting around this involves calculating the width of thestring in twips before converting it to pixels to display. If there is more thanone letter per pixel then the string length cannot be properly calculatedin pixels.Drawing the textWe can see how our allocated font is used in the DrawInRect()function:void CExampleHelloView::DrawInRect(const MGraphicsDeviceMap& aMap,CGraphicsContext& aGc, const TRect& aDeviceRect, CFont* aFont){// Draw some textif (iFullRedraw){aGc.SetBrushStyle(CGraphicsContext::ESolidBrush);aGc.SetBrushColor(KRgbWhite);}else aGc.SetBrushStyle(CGraphicsContext::ENullBrush);aGc.SetPenStyle(CGraphicsContext::ESolidPen);aGc.SetPenColor(KRgbBlack);aGc.UseFont(aFont);TInt baseline = aDeviceRect.Height()/2 + aFont->AscentInPixels()/2;aGc.DrawText(*iText, aDeviceRect, baseline, CGraphicsContext::ECenter);aGc.DiscardFont();// Draw a surrounding box...}This uses the version of DrawText() that specifies a rectangle andguarantees that drawing will be clipped within that rectangle.

However,the DrawText() function will only white out the background beforedrawing if iFullRedraw is set. When it is set, the brush setting is solidand white, which causes the background to be drawn in white; when itis not set, there is effectively no brush and the text is drawn straight overwhatever was there before, which is the dialog default background imageDEVICE- AND SIZE-INDEPENDENT GRAPHICS541drawn by the UI framework.

In a real program, redrawing the backgroundwould not be conditional; depending on the needs of the application,the user interface and the particular phone, an application would alwayseither use an image drawn by the framework or explicitly draw whateverbackground it requires.Using the viewCExampleHelloControl has a CExampleHelloView, which it usesfor drawing its model:void CExampleHelloControl::Draw(const TRect& /*aRect*/) const{CWindowGc& gc = SystemGc(); //CWindowGc is derived from CGraphicsContextTRect rect = Rect();rect.Shrink(10,10);gc.SetPenStyle(CGraphicsContext::ENullPen);gc.SetBrushStyle(CGraphicsContext::ESolidBrush);gc.SetBrushColor(KRgbWhite);DrawUtils::DrawBetweenRects(gc, Rect(), rect); // whitens the bordergc.SetPenStyle(CGraphicsContext::ESolidPen);gc.SetPenColor(KRgbBlack);gc.SetBrushStyle(CGraphicsContext::ENullBrush);gc.DrawRect(rect);rect.Shrink(1,1);iView->DrawInRect(iZoomFactor, gc, rect, iFont);}First, CExampleHelloControl draws a surrounding 10-pixel border.

This code is guaranteed to be on the screen and the 10-pixel borderis chosen independently of the zoom state (as it would look silly if theborder were to scale to honor the zoom state).The code is written to ensure that we draw every pixel. The callto DrawUtils::DrawBetweenRects() paints white into the regionbetween the rectangle containing the text and the outside of the control.We use the pen to draw a rectangle just inside the rectangle’s border.Then the rectangle is shrunk by a pixel and passed to the Hello view’sdraw function.The fundamental point that this example shows is that you can implement drawing code that is completely independent of a control and thescreen device.Managing the zoom factorCExampleHelloControl shows how the zoom factor of a device maprelates to the device.

Here is the declaration of TZoomFactor in gdi.h:class TZoomFactor : public MGraphicsDeviceMap{542GRAPHICS FOR DISPLAYpublic:IMPORT_C TZoomFactor();IMPORT_C ∼TZoomFactor();inline TZoomFactor(const MGraphicsDeviceMap* aDevice);IMPORT_C TInt ZoomFactor() const;IMPORT_C void SetZoomFactor(TInt aZoomFactor);inline void SetGraphicsDeviceMap(const MGraphicsDeviceMap* aDevice);inline const MGraphicsDeviceMap* GraphicsDeviceMap() const;IMPORT_C void SetTwipToPixelMapping(const TSize& aSizeInPixels,const TSize& aSizeInTwips);IMPORT_C TInt HorizontalTwipsToPixels(TInt aTwipWidth) const;IMPORT_C TInt VerticalTwipsToPixels(TInt aTwipHeight) const;IMPORT_C TInt HorizontalPixelsToTwips(TInt aPixelWidth) const;IMPORT_C TInt VerticalPixelsToTwips(TInt aPixelHeight) const;IMPORT_C TInt GetNearestFontInTwips(CFont*& aFont,const TFontSpec& aFontSpec);IMPORT_C void ReleaseFont(CFont* aFont);public:enum {EZoomOneToOne = 1000};private:TInt iZoomFactor;const MGraphicsDeviceMap* iDevice;};TZoomFactor both implements MGraphicsDeviceMap’s interfaceand uses an MGraphicsDeviceMap.

TZoomFactor contains an integer, iZoomFactor, which is set to 1000 to indicate a one-to-one zoom,and proportionately for any other zoom factor. In order to implementa function such as VerticalTwipsToPixels(), TZoomFactor usescode such as the following:EXPORT_C TInt TZoomFactor::VerticalTwipsToPixels(TInt aTwipHeight) const{return iDevice->VerticalTwipsToPixels((aTwipHeight*iZoomFactor)/1000);}TZoomFactor scales the arguments before passing the function callon to its MGraphicsDeviceMap.

Other functions combine the zoomand conversion between pixels and twips:• a pixels-to-twips function scales after calling pixels-to-twips on thedevice map• a get-nearest-font function scales the font’s point size before callingget-nearest-font on the device map.The function names in TZoomFactor indicate several ways to set thezoom factor. The method we use in CExampleHelloControl is themost obvious one:void CExampleHelloControl::SetZoomAndDeviceDependentFontL(TInt aZoomFactor)DEVICE- AND SIZE-INDEPENDENT GRAPHICS543{iZoomFactor.SetZoomFactor(aZoomFactor);...}GetZoom() works the other way round:TInt CExampleHelloControl::GetZoom() const{return iZoomFactor.ZoomFactor();}The SetZoomInL() function works in a reasonably standard way,cycling between six hard-coded zoom factors:void CExampleHelloControl::SetZoomInL(){TInt zoom = GetZoom();zoom = zoom < 250 ? 250 :zoom < 500 ? 500 :zoom < 1000 ? 1000 :zoom < 1500 ? 1500 :zoom < 2000 ? 2000 :zoom < 3000 ? 3000 :250;SetZoomAndDeviceDependentFontL(zoom);}SetZoomOutL() works the other way round.

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