Главная » Просмотр файлов » 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), страница 19

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

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

Figure 5.5 shows an example: on the left,there is the original image and, on the right, the corresponding mask thatmasks out the background of the arrow.Figure 5.5 An image and its corresponding maskThen, you can load and use the mask to copy only the visible parts,defined by the mask, mask img, of the source image, src img, to thecanvas as follows:mask_img = Image.new(size = (50, 50), mode = '1')mask_img.load('e:\\Images\\mask_img.png')src_img = graphics.Image.open('e:\\Images\\orig_img.png')canvas.blit(src_img, target=(0,0), source=(0,0), mask = mask_img)The parameter mode = "1" specifies that the new image, mask img,has only two colors, black and white.

This mode is required for masks.Section 11.5 presents an example that uses masks extensively.5.3.5 Taking a ScreenshotThe view that is visible on the phone’s screen can be captured with thefunction graphics.screenshot(). This function converts the currentGRAPHICS97view to a new Image object and returns it to the caller. Example 32 takesa screenshot of itself and saves it to a file.Example 32: Screenshotimport graphicsprint "Hi there!"img = graphics.screenshot()img.save(u"e:\\Images\\screenshot.png")Note that if you have a new memory card, it might not have the Imagesdirectory.

In this case, use the phone’s default camera application toshoot and save a photo to the memory card. This will create the requireddirectory.Screenshots that appear in this book were taken as follows: we used thee32.Ao timer object to call a function after a certain time period – seeExample 50 for a similar usage of the timer. The function contained thesame lines as the example above. For each figure, we calibrated the delayso that the screen would contain the exact arrangement we wanted tocapture.5.3.6 Interactive GraphicsIn Example 33, we learn how to move a single black point, leavingtraces, on a white background (someone might call this a pen), as shownin Figure 5.6. This example combines earlier lessons learnt, namelydrawing graphics primitives and handling keyboard events.Figure 5.6Moving dot with its trace98SOUND, INTERACTIVE GRAPHICS AND CAMERAExample 33: Moving graphicsimport appuifw, graphics, e32, key_codesBLACK = (0, 0, 0)WHITE = (255, 255, 255)key_down = Noneclicked = Nonedef handle_event(event):global clicked, key_downif event['type'] == appuifw.EEventKey:if key_down:key_down = (event['keycode'], "down")else:key_down = (event['keycode'], "pressed")elif event['type'] == appuifw.EEventKeyUp and key_down:code, mode = key_downif mode == "pressed":clicked = codekey_down = Nonedef key_is_down(code):if key_down and key_down == (code, "down"):return Truereturn Falsedef quit():global runningrunning = Falsedef handle_redraw(rect):if img:canvas.blit(img)img = Nonecanvas = appuifw.Canvas(event_callback = handle_event,redraw_callback = handle_redraw)appuifw.app.screen = "full"appuifw.app.body = canvasappuifw.app.exit_key_handler = quitx = y = 100w, h = canvas.sizeimg = graphics.Image.new((w, h))img.clear(WHITE)running = Truewhile running:if key_is_down(key_codes.EKeyLeftArrow): x -= 5elif key_is_down(key_codes.EKeyRightArrow): x += 5elif key_is_down(key_codes.EKeyDownArrow): y += 5elif key_is_down(key_codes.EKeyUpArrow): y -= 5#img.clear(WHITE)GRAPHICS99img.point((x, y), outline = BLACK, width = 50)handle_redraw(None)e32.ao_yield()The functions handle event() and key is down() are familiarfrom Example 30.

Again, we create a separate image, img, on which thedot is first drawn and then the whole image is copied onto the canvasin handle redraw().The dot is moved with the arrow keys. Depending on which arrow isheld down, we move the dot’s location the corresponding direction in xand y coordinates. Here the dot is moved 5 pixels at time, but you canexperiment with different values.The e32.ao yield() at the end of the loop makes sure that thesystem leaves some time to register the keyboard events, as drawing inthe tight loop consumes lots of CPU power and might make the systemunresponsive.Actually, since we move the dot only when the user presses a key, wecould have used the approach of Example 28 to handle the key events.In this case, we would not need the busy loop at the end, which wouldmean less computing and savings in precious battery time.

However, thisexample should prepare you for Example 39, where the loop is actuallynecessary.One line, img.clear(WHITE), is preceded by the hash mark (#)which means that the line is a comment and is ignored by the PyS60interpreter. If you remove the hash mark, the line is executed and the dotdoes not leave any traces. Note, however, that clearing the whole imagebecause the dot has moved one step forward is unnecessarily expensive.A better, but less straightforward, approach for clearing traces would beto draw a small white rectangle on top of the old dot before drawing thenew dot.5.3.7 3D GraphicsPython for S60 provides support for 3D graphics by way of the modulesgles and glcanvas.

The gles module contains Python bindings to theOpenGL ES 2D and 3D graphics API. The glcanvas module providesan object for displaying the 3D graphics, in the same way as the Canvasobject is used to display 2D graphics.Making 3D graphics with OpenGL is somewhat complicated. Fortunately, several good books and free tutorials have been written about thesubject. Thus, we do not go into details here. A good starting point is,for instance http://pyopengl.sourceforge.net, which explains a Pythonversion of the OpenGL graphics. The Python for S60 version follows theseconventions closely.100SOUND, INTERACTIVE GRAPHICS AND CAMERAFigure 5.7 OpenGL cubeWe provide a teaser for 3D graphics on this book’s website.

There youcan find an example of a 3D cube, shown in Figure 5.7, which spins onthe x, y and z axes simultaneously.5.4 CameraFor using the built-in camera of an S60 phone, PyS60 offers a modulenamed camera. We think that this is one of the most fun modules inPyS60, as it can give your programs a new view of the surrounding world.Because of our enthusiasm for the camera module, this book includesseven examples that are based on taking photos. Being able to usethe camera programmatically – even in the most esoteric ways – maychange your relationship with camera phones in a profound manner.

Forinstance, see Section 11.2 for a description of a large-scale urban photohunt that was implemented using the camera module! The cameramodule includes three types of functions: to query features of the camera;to open and close the viewfinder; and to take photos.Note that the camera consumes a lot of energy. If you have anapplication that uses the viewfinder or takes photos frequently, in manycases it is necessary to recharge the battery after four or five hours.5.4.1 Querying Features of the CameraThe following functions are available in the camera module to querycamera-related features of your phone:CAMERA101•cameras available() returns the number of cameras availablein the device.•image modes() returns the image modes supported by the deviceas a list of strings, for example: [RGB12, RGB16, RGB] (the last onecorresponds to full-color images).•image sizes() returns the image resolutions supported by thedevice as a list of (w, h) tuples, for example: [(640, 480), (160, 120)].• flash modes() returns the flash modes supported by the device asa list of strings.•max zoom() returns the maximum digital zoom value supported bythe device as an integer.• exposure modes() returns the exposure settings supported by thedevice as a list of strings.• white balance modes() returns the white-balance modes supported by the device as a list of strings.5.4.2 Using the ViewfinderTaking a good photo is difficult if you get no visual feedback for aimingthe camera.

For this purpose, the viewfinder, like the one shown inFigure 5.8, produces a stream of Image objects that are produced by thecamera in real-time. It is up to you what to do with these images, butFigure 5.8 Viewfinder102SOUND, INTERACTIVE GRAPHICS AND CAMERAtypically you want to show them on the canvas, to help the user aim thecamera properly.Example 34: Viewfinderimport camera, appuifw, e32def viewfinder(img):img.point((100, 100), outline = (255, 0, 0), width = 10)canvas.blit(img)def quit():camera.stop_finder()lock.signal()appuifw.app.body = canvas = appuifw.Canvas()appuifw.app.exit_key_handler = quitcamera.start_finder(viewfinder)lock = e32.Ao_lock()lock.wait()The function camera.start viewfinder() takes a single parameter, a callback function that handles the incoming images.

In this case,the job is handled by the function viewfinder. To convince you thatthe viewfinder images are just normal Image objects, we draw a smallred dot on each image before showing it on the canvas.The camera.start viewfinder() function accepts two optionalparameters besides the callback function:•backlight defines whether the device backlight is kept on whenthe camera viewfinder is in operation. backlight = 1 makes it on,which is the default, and 0 off.•size defines the viewfinder image size, as in size = (176, 144).It is important to stop the viewfinder, using the camera.stopfinder() function, once you do not need it, otherwise it may keep thecamera busy in the background and drain the battery quickly.5.4.3 Taking a PhotoThe most important functionality that one expects from a camera is totake a photo.

Without further ado, here is how to do it.Example 35: Minimalist cameraimport cameraphoto = camera.take_photo()photo.save("E:\\Images\\minicam.jpg")CAMERA103The function camera.take photo() returns the photo as an Imageobject. With photo.save('E:\\Images\\minicam.jpg') thephoto is saved to the image gallery of the phone. If some other applicationis using the camera when you start this script, the program fails and anerror is shown.After trying Example 35, you are probably delighted to see Example 36,which lets you use the viewfinder before taking a photo.Example 36: Taking photos with a viewfinderimport e32, camera, appuifw, key_codesdef viewfinder(img):canvas.blit(img)def shoot():camera.stop_finder()photo = camera.take_photo(size = (640, 480))w, h = canvas.sizecanvas.blit(photo, target = (0, 0, w, 0.75 * w), scale = 1)image.save('e:\\Images\\photo.jpg')def quit():app_lock.signal()appuifw.app.body = canvas = appuifw.Canvas()appuifw.app.title = u"Camera"appuifw.app.exit_key_handler = quitcamera.start_finder(viewfinder)canvas.bind(key_codes.EKeySelect, shoot)app_lock = e32.Ao_lock()app_lock.wait()First we initialize the application UI and assign a canvas to theapplication body in a familiar way.

We bind the Select key to the functionshoot() that is used to take the actual photo – this corresponds tothe first approach to handling the keyboard keys, in Section 5.2.1. Theviewfinder functionality is based on Example 34.Once the user clicks the Select key, the function shoot() is called.First the viewfinder is closed, which freezes the latest image on the screen,so that the user can see that the camera is taking the photo. Then we takethe actual photo with the camera.take photo() function. This maytake a few seconds and you should hold the camera still during this time.Once the photo, photo, is ready, we show it on the canvas.

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

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

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

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