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

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

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

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

If the application needs to initiate drawing of a control, itshould call either DrawNow() or DrawDeferred().The application may call DrawNow() on a control after it has beencreated and is ready for drawing, or if a change in application data or theDRAWING A CONTROL447control’s internal state means that entire control’s appearance is no longerup to date. If the control is not ready to be drawn, that is, if it is eitherinvisible or not yet activated, DrawNow() does nothing. Otherwise, fora normal window-owning control, DrawNow() surrounds a call to thecontrol’s Draw() function with a call to the window’s Invalidate()function and the other window-server-related housekeeping that wasmentioned earlier.

For a compound control, it also generates calls to theDrawNow() function of each of the component controls.For a complex control, partial redrawing of the control may sometimesbe more appropriate than drawing the entire control. One example iswhere a user adds a character in a word processor. Instead of drawingthe whole control, redrawing only the area of the screen occupied by thenew character reduces processing and can improve performance. In sucha case you should not use DrawNow() but will need to write your owncustomized drawing code. See Chapter 17 for more information on thistopic.As an alternative to calling DrawNow(), you may choose to call acontrol’s DrawDeferred() function, which simply causes the control’sarea to be marked as invalid, eventually causing the window server toinitiate a redraw.

The control framework handles redraw events at a lowerpriority than user-input events, which means that any pending user-inputevents will be processed before the redraw event. DrawDeferred()therefore allows a control to do drawing at a lower priority than drawingperformed by DrawNow().An advantage of using DrawDeferred() is that if you make multiplecalls to DrawDeferred() on the same area of a control, the windowserver will not generate a redraw event to do drawing that has alreadybeen superseded. If you make multiple calls to DrawNow(), however,all of them get processed, even if they have already been superseded bythe time they are processed.In the Noughts and Crosses application, a tile’s TryHitL() functioncalls DrawDeferred() following a successful attempt to set the tile tocontain a nought or a cross.Void COandXTile::TryHitL(){if (iAppView->TryHitSquareL(this)){DrawDeferred();)}If DrawNow() were used here, the control would be drawn twice inthe case where a pointer event switched focus to this control as well assetting it to contain a nought or a cross.Both DrawNow() and DrawDeferred() are implemented byCCoeControl and may not be overridden.448CONTROLSThe Draw() FunctionThe Draw() function needs to be implemented by all non-blank controls, but is intended to be called only from the control’s own memberfunctions, hence Draw() is declared as a private member function ofCCoeControl.The function is passed a reference to a TRect, indicating the region ofthe control that needs to be redrawn, and the function must guarantee todraw to every pixel within the rectangle.

It may, subject to considerationsof efficiency, ignore the rectangle and draw the whole of the control. However, drawing outside the specified rectangle may slow down drawing.Depending on how drawing is implemented and the complexity of whatis being drawn, this could potentially result in visible flicker in the display.The Draw() function should not draw outside the control’s area. Forwindow-owning controls, drawing is clipped to the window boundary,so drawing outside the control will only reduce efficiency. Drawing isnot clipped to the boundary of a non-window-owning control, so in thiscase it is essential that the control does not draw outside its boundary.You may safely assume that:• before any Draw() function is called, the graphics context has beenactivated and its properties set to their defaults• the graphics context is deactivated for you after the return fromDraw().Your implementation of Draw() should gain access to a CWindowGcgraphics context by means of a call to SystemGc(), and all drawingshould be done using this graphics context.In the Noughts and Crosses example, responsibility for drawing isdivided between the view and the component tiles.

The view draws onlythe outer regions and the lines between the tiles.void COandXAppView::Draw(const TRect& /*aRect*/) const{CWindowGc& gc = SystemGc();TRect rect = Rect();// Draw outside the bordergc.SetPenStyle(CGraphicsContext::ENullPen);gc.SetBrushStyle(CGraphicsContext::ESolidBrush);gc.SetBrushColor(KRgbWhite);DrawUtils::DrawBetweenRects(gc, rect, iBorderRect);// Draw a border around the boardgc.SetBrushStyle(CGraphicsContext::ESolidBrush);gc.SetBrushColor(KRgbGray);DrawUtils::DrawBetweenRects(gc, iBorderRect, iBoardRect);// Draw the first vertical linegc.SetBrushColor(KRgbBlack);DRAWING A CONTROL449TRect line;line.iTl.iX = iBoardRect.iTl.iX + iTileSide;line.iTl.iY = iBoardRect.iTl.iY;line.iBr.iX = line.iTl.iX + KLineWidth;line.iBr.iY = iBoardRect.iBr.iY;gc.DrawRect(line);TInt i;// Draw the remaining (KTilesPerRow-2) vertical linesfor (i = 0; i < KTilesPerRow - 2; i++){line.iTl.iX += iTileSide + KLineWidth;line.iBr.iX += iTileSide + KLineWidth;gc.DrawRect(line);}// Draw the first horizontal lineline.iTl.iX = iBoardRect.iTl.iX;line.iTl.iY = iBoardRect.iTl.iY + iTileSide;line.iBr.iX = iBoardRect.iBr.iX;line.iBr.iY = line.iTl.iY + KLineWidth;gc.DrawRect(line);// Draw the remaining (KTilesPerCol-2) horizontal linesfor (i = 0; i < KTilesPerCol - 2; i++){line.iTl.iY += iTileSide + KLineWidth;line.iBr.iY += iTileSide + KLineWidth;gc.DrawRect(line);}}The lines are drawn as thin rectangles rather than using gc.DrawLine().

This ensures that the lines cover the precise region we want,without the need for messy calculations involving the line width, and weavoid potential problems related to the rounded ends of lines.Each tile is responsible for drawing itself.void COandXTile::Draw(const TRect& /*aRect*/) const{TInt tileType;tileType = iAppView->SquareStatus(this);CWindowGc& gc = SystemGc();TRect rect = Rect();if (IsFocused()){gc.SetBrushColor(KRgbYellow);}gc.Clear(rect);if (tileType!=ETileBlank){DrawSymbol(gc, rect, tileType==ETileCross);}}First we check if the tile is empty or not with a call to SquareStatus().450CONTROLSThen the tile background is drawn.

Note that the background color isset to yellow only for the tile that currently has focus. White is the defaultbrush color, and we can safely assume that the graphics context defaultshave been set before Draw() was called.Highlighting the control with focus isn’t always necessary. The Noughtsand Crosses application running on, say, the Sony Ericsson P990 (usingUIQ) doesn’t receive key events. You don’t need a tile to be highlightedin order to know whether you can tap on it to enter a nought or a cross.Having drawn the background, we use the status of the tile againto determine whether we need to draw a red circle or a green cross.The relevant symbol is drawn by means of a call to DrawSymbol(),which is implemented in the COandXSymbolControl superclass (seeChapter 12).void COandXSymbolControl::DrawSymbol(CWindowGc& aGc, TRect& aRect,TBool aDrawCross) const{TSize size;size.SetSize(aRect.iBr.iX - aRect.iTl.iX, aRect.iBr.iY - aRect.iTl.iY);aRect.Shrink(size.iWidth/6,size.iHeight/6); // Shrink by about 15%aGc.SetPenStyle(CGraphicsContext::ESolidPen);size.iWidth /= 9; // Pen size set to just over 10% of shape's sizesize.iHeight /= 9;aGc.SetPenSize(size);if (aDrawCross){aGc.SetPenColor(KRgbGreen);// Cosmetic reduction of cross size by half the line widthaRect.Shrink(size.iWidth/2, size.iHeight/2);aGc.DrawLine(aRect.iTl, aRect.iBr);TInt temp;temp = aRect.iTl.iX;aRect.iTl.iX = aRect.iBr.iX;aRect.iBr.iX = temp;aGc.DrawLine(aRect.iTl, aRect.iBr);}else // draw a circle{aGc.SetPenColor(KRgbRed);aGc.SetBrushStyle(CGraphicsContext::ESolidBrush);aGc.DrawEllipse(aRect);}};This isn’t ideal drawing code, as we’re drawing over an area thatwe have previously blanked.

That means there is some potential forthe display to flicker; ideally, each pixel should only be drawn once.BACKED-UP WINDOWS451However, the redrawing is confined to a small region and is doneimmediately, so in practice the display behavior is acceptable.Before drawing the cross, we shrink the bounding rectangle by half theline width: without this, a cross would look slightly larger than a nought.It’s always worth paying attention to such details in an application, tocreate the best possible impression on the user.In conclusion, these two functions do indeed satisfy the basic requirements for the effective drawing of a control:• the combined drawing code of the view and the tiles covers everypixel of the required area• neither function draws outside the relevant control• apart from the redrawing of the nought and cross symbols, each pixelis drawn only once.15.7 Backed-up WindowsIn the window server, a standard window is represented by informationabout its position, size, visible region, and invalid region – and that’sabout all.

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

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

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

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