Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 18

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 18 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 182018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

For instance, you could have a key combination that triggersan action regardless of the application that you are using on the phone.92SOUND, INTERACTIVE GRAPHICS AND CAMERAThe keycapture module provides a KeyCapturer object that isused for listening to the events by way of a callback function. The callbackis called each time any of the specified keys is pressed.Since capturing all key presses on your phone has security and privacyimplications, 3rd Edition phones require a special capability (SwEvent) touse this module. See Appendix A for more information about capabilities.5.3 GraphicsWhen we want to display 2D graphics or images on the screen, theCanvas object is needed in the application body. Canvas is a UI elementthat provides a drawable area on the screen but it also provides supportfor handling keyboard events, as we saw in Section 5.2.

We showed howto create a canvas object and how to assign it to the application body. Wealso mentioned that it has an optional parameter, redraw callback,that defines a callback function that is called whenever a part of thecanvas must be redrawn. Typically, this happens when the user switchesaway from the Python application and back again or after a popup menuis displayed.5.3.1 Drawing Graphics PrimitivesThis section shows you how to draw circles, rectangles, lines andpoints – that is, all kinds of graphics primitives. A common way toperform drawing and showing graphics on the screen is that you first create a graphics.Image object, manipulate that object and then draw iton the canvas (screen) in the redraw callback function.This process is called double buffering.

The name refers to the fact thatinstead of drawing primitives directly on the canvas, which is possible aswell, you draw them in a separate image (buffer) first. This way you donot have to draw everything again when the canvas must be redrawn, forexample after a popup dialog has cleared a part of the canvas.

Instead,you simply copy the image to the canvas. The Image.blit() functionthat handles the copying is typically accelerated by hardware and is, thus,fast.To do this, we need to import the graphics module, which givesaccess to functions for drawing graphics primitives and loading, saving,resizing and transforming images. It is loosely based on the PythonImaging Library (PIL), though it supports only a restricted set of itsfunctions.Let’s have a look at the graphics module.

Example 31 draws a redpoint, a yellow rectangle and some white text to the screen, as shown inFigure 5.4. We use keyboard keys to draw one of these graphics primitiveson the screen or to draw all primitives at the same time.GRAPHICSFigure 5.4Graphics primitives drawn to the screenExample 31: Graphics primitivesimport appuifw, e32, key_codes, graphicsWHITE = (255,255,255)RED = (255,0,0)BLUE = (0,0,255)YELLOW = (255,255,0)def draw_rectangle():img.rectangle((50,100,100,150), fill = YELLOW)def draw_point():img.point((90,50), outline = RED, width = 30)def draw_text():img.text((10,40), u"Hello", fill = WHITE)def handle_redraw(rect):if img:canvas.blit(img)def handle_event(event):ev = event["keycode"]if event["type"] == appuifw.EEventKeyDown:img.clear(BLUE)if ev == key_codes.EKeyUpArrow:draw_point()elif ev == key_codes.EKeyRightArrow:draw_text()elif ev == key_codes.EKeyDownArrow:draw_rectangle()elif ev == key_codes.EKeyLeftArrow:9394SOUND, INTERACTIVE GRAPHICS AND CAMERAdraw_point()draw_text()draw_rectangle()handle_redraw(None)def quit():app_lock.signal()img = Nonecanvas = appuifw.Canvas(redraw_callback = handle_redraw,\event_callback = handle_event)appuifw.app.body = canvasappuifw.app.screen = "full"appuifw.app.exit_key_handler = quitw, h = canvas.sizeimg = graphics.Image.new((w, h))img.clear(BLUE)app_lock = e32.Ao_lock()app_lock.wait()At the beginning of the script we assign various colors to constants:WHITE, RED, BLUE and YELLOW.

The color representation consists of athree-element tuple of integers in the range from 0 to 255, representingthe red, green and blue (RGB) components of the color.If you have written some HTML code, you may be familiar with thehexadecimal representation of a color: in this case, the color is specifiedas a value such as 0xRRGGBB, where RR is the red, GG the green andBB the blue component of the color, each of which is a hexadecimalvalue from 0x0 to 0xff (0–255). Using this notation, we could specify, forinstance, YELLOW = 0xffff00.Next we define three functions, each of which handles the drawing ofa single primitive:•draw rectangle(): the first tuple specifies the top-left and lowerright corners of the rectangle, in format (x1, y1, x2, y2) and the fillparameter defines its color.•draw point(): the first tuple specifies the center of the point at(x,y).

The parameter width specifies the size in pixels and outlinespecifies the color.•draw text(): draws the Unicode string u"Hello" on image at thespecific location that is defined in the first tuple.Toward the bottom of the script you can see the following lines:w, h = canvas.sizeimg = graphics.Image.new((w, h))GRAPHICS95They create a new Image object whose size equals to the canvas.

Before these lines, notice that we create a Canvas object andassign two callback functions to it, which handle redrawing of the canvas and key events, correspondingly. As you might guess, the functionimg.clear(BLUE) clears the image to blue initially.

Note that theimage should be created only after the Canvas object is assigned tothe application body. Otherwise canvas.size may return an incorrecttuple for the screen size.The function handle event() draws the primitives on the image,img, depending on which key is pressed. When any key is pressed down,the image is first cleared for drawing.

Then, a point, text, a rectangle orall of these are drawn in the respective functions, based on the actualkeycode. Finally, we request the canvas to be redrawn by calling thefunction handle redraw().The function handle redraw() is simple: it gets a single parameter,rect, that defines the area on the screen that must be redrawn.

Forsimplicity, we may omit this parameter and always redraw the wholescreen. A performance-critical application, say a game, might use therect parameter to speed up redrawing if only a fraction of the canvasmust be refreshed.Both the Image and Canvas objects have a blit() function thatis used to copy one image to another. In this case, we copy img tothe canvas as whole, thus no additional parameters are specified for thefunction.

The if clause ensures that no blitting is performed until imghas been initialized appropriately.5.3.2 More on Graphics PrimitivesBesides the primitives point, rectangle and text, there are otherprimitives available, such as line, polygon, ellipse and pieslice.You can also change the font and size of the text primitive.

For moreinformation, see the PyS60 documentation. The graphics module alsooffers several image-manipulation methods for resizing, flipping androtating images, which are described in the documentation.Chapter 11 contains more advanced examples that use the graphicsmodule. In particular, have a look at Section 11.3, which describes anartistic tool called MobileArtBlog in detail. The tool combines the powerof the camera and graphics modules in an innovative way: you canpick patterns from your physical environment and use them as paintbrushes!With the help of the graphics primitives, you can also design UIelements of your own, instead of using the native UI elements of the S60platform. This is demonstrated in Sections 11.2 and 11.5.96SOUND, INTERACTIVE GRAPHICS AND CAMERA5.3.3 Loading and Saving ImagesInstead of using graphics primitives, you can use photos and othergraphical material in the JPEG or PNG formats.

The handling of thesematerials is done through the Image object in a similar way to the waygraphics primitives are handled. Note that once a pre-made image hasbeen loaded, you can use it in the same way as any other Image object,for example, any of the above graphic primitives can be drawn on it.A pre-made image is loaded and saved to a new file as follows:img = graphics.Image.open("e:\\Images\\picture.jpg")img.save("e:\\Images\\picture_new.jpg")5.3.4 Image MasksWhen you copy one image to another using the blit() function, theshape of the source image is rectangular by default. In some cases, this isnot desirable and you would like to mask out certain parts of the sourceimage.For this purpose, you need a black and white mask image with thevisible parts painted in white.

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

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

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

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