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

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

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

In general, they areused to fill a shape that is drawn onto the screen. Default color for thebrush is white and the default style is Null. Null brush means that no fillingis used, thus the area is drawn transparent and the original background isshown under the shape drawn to the screen. Styles that can be set for thebrush are:• ESolidBrush (background is filled with solid color).• EPatternedBrush (brush image is used as background).• EVerticalHatchBrush (brush fills the shape with vertical hatchinglines).• EForwardDiagonalHatchBrush (brush fills the shape with diagonal hatching lines).• EHorizontalHatchBrush (brush fills the shape with horizontalhatching lines).• ERearwardDiagonalHatchBrush (brush fills the shape with rearward diagonal hatching lines).• ESquareCrossHatchBrush (brush fills the shape with horizontaland vertical hatching lines).• EDiamondCrossHatchBrush (brush fills the shape with forwarddiagonal and rearward diagonal hatching lines).With brush fillings, the brush color will define the background colorand the pen color is used with the lines (if the brush style has linesin it).

When using brush patterns, after you have finished using thebrush, you should call DiscardBrushPattern() to release the brushpattern’s memory.GRAPHICS AND DRAWING199Another notable issue is that if the size of the brush image is smallerthan the brush area, the image will be tiled – thus if you want to fill thewhole drawing area with the image without having it tiled, you shouldeither scale the image beforehand so it fits the whole screen nicely, orjust draw the image as per usual to fill the screen and then use Null brushwith all other drawing.After you have set the brush, you could fill the whole container areawith it by calling gc.Clear() in the Draw() function, or draw it to anyselected shape as shown in the following code sample:void Draw( const TRect& aRect) const{CWindowGc& gc = SystemGc();gc.SetBrushColor(KRgbWhite);gc.SetBrushStyle(CGraphicsContext::ESolidBrush);gc.DrawRect(aRect);}What may go wrong when you do this: When using a patterned brush,the brush bitmap needs to be set first by calling the UseBrushPattern() function.

If you call SetBrushStyle(CGraphicsContext::EPatternedBrush) without first setting a valid bitmap,it will cause a panic.Tip: When using bitmaps, an important issue to remember is that evenwhen the pointer for the bitmap is valid, the content could still beinvalid – and using this type of image will generate a panic for sure.To avoid such a problem, you should always first check the pointerof the bitmap and then also that it has a valid (that is, a non-NULL)handle.4.5.1.3Load and Draw MBM or MIF ImagesAmount of time required: 15 minutesLocation of example code: \Graphics_ImagesRequired library(s): efsrv.lib, bitgdi.lib, w32.libRequired header file(s): f32file.h, bitstd.h, w32std.hRequired platform security capability(s): NoneProblem: You want to load an image that is stored in a Symbian OSproprietary multi-image file (MBM or MIF) and draw it to the screen.Solution: On Symbian OS, images may be stored in a proprietary multiimage file (MBM for bitmaps and MIF for scalable images).200SYMBIAN C++ RECIPESFirst, you need to locate the image file.

Usually you can’t know inwhich drive the application is installed, thus you don’t know from whichdrive to load the image. To locate the image you could, for example, useTFindFile and just specify the full path with filename and extension,and let the API find the drive the file is stored in.Files can then be loaded directly with a CFbsBitmap-type object, byfirst constructing the object and then calling its Load() function. TheLoad() function takes two arguments, of which the first is the imagename and the second the index of the image stored in the multi-imagefile. Note that the index is zero-based, thus the first image’s index is 0.The code for locating and loading a bitmap at index 0 in a file calledbitmap.mbm is shown in the following code sample:_LIT(KtxBitmapFile,"\\private\\A0003139\\bitmap.mbm");TFindFile imageFile(CCoeEnv::Static()->FsSession());if(KErrNone == imageFile.FindByDir(KtxBitmapFile, KNullDesC)){iBrushBitmap = new(ELeave) CFbsBitmap();iBrushBitmap->Load(imageFile.File(),0);}After loading the image you can draw it to the screen in the Draw()function like this:void CMyContainer::Draw(const TRect& aRect) const{CWindowGc& gc = SystemGc();gc.DrawBitmap(Rect(), iBitmap);}What may go wrong when you do this: The Load() function used forloading the image will return an error code if the loading fails.

In casethe error is not checked, you need to check the handle for the imagebefore drawing it. Trying to draw an image in which loading failedwill generate a panic.4.5.1.4Draw an Image with a Transparent SectionAmount of time required: 15 minutesLocation of example code: \Graphics_ImagesRequired library(s): efsrv.lib, bitgdi.lib, w32.libRequired header file(s): f32file.h, bitstd.h, w32std.hRequired platform security capability(s): NoneProblem: The image you want to draw contains at least partially transparent pixels.GRAPHICS AND DRAWING201Solution: When you want to draw images with transparent sections, youneed to have firstly the bitmap image to show and then a 1-pixel blackand white image which masks the background with the image. Thus, thistime you need to load two different images:// bitmapFile is a TFindFileiBall = new(ELeave) CFbsBitmap();iBall->Load(bitmapFile.File(),1);iMask = new(ELeave) CFbsBitmap();iMask->Load(bitmapFile.File(),2);void CMyContainer::Draw(const TRect& aRect,) const{CWindowGc& gc = SystemGc();TSize imageSize(iBall->SizeInPixels());TRect destRect(0,0, imageSize.iWidth, imageSize.iHeight);TRect sourceRect(0,0, imageSize.iWidth, imageSize.iHeight);gc.DrawBitmapMasked(destRect, iBall, sourceRect, iMask, ETrue);}Discussion: With the mask, usually the black pixels are the ones thatwill show the image and the white ones are the ones that will show thebackground, but you can define the mask to work the other way aroundby changing the last argument in the DrawBitmapMasked() functionto be EFalse.Tip: The first argument to DrawBitmapMasked() is the destinationrectangle to which the image is to be drawn.

This looks like you couldask for the image to be scaled to your requirements, but using thiswould not be a good idea. Some phones will do this correctly, butin some devices you would get distorted images. It is advisable topre-scale all masked images and then draw them the size they are.One way to scale an image is to draw it into an off-screen image thatis constructed to the desired size (Recipe 4.5.3.1 explains how to dothis in more detail).The rectangle argument defined between the image and the maskis a source rectangle, defining which part of the image is to be drawninto the target.

If you bear in mind the previous advice and change thisto anything other than the original rectangle of the image, you need toadjust the destination rectangle size as well.4.5.2 Intermediate Recipes4.5.2.1Load a JPG or PNG ImageAmount of time required: 15 minutesLocation of example code: \Graphics_Images202SYMBIAN C++ RECIPESRequired library(s): bitgdi.lib, ws32.lib, imageconversion.lib, apgrfx.lib, apmime.libRequired header file(s): bitstd.h, w32std.h, ImageData.h,imageconversion.h, apgcli.h, apmrec.hRequired platform security capability(s): NoneProblem: You want to load and draw image files other than those storedin MBM or MIF files.Solution: To load an image file other than a MBM or MIF image, youneed to use the Symbian OS image converter library (ICL), which canconvert single and multiframe images stored in files or descriptors toCFbsBitmap objects for rendering to the screen. When opening imagefiles, you first need to know which type of image you are dealing with.For this purpose you could use RApaLsSession as shown in the GetFileType() function, or simply use the static GetMimeTypeFileL()function provided with the CImageDecoder class.The file type defines the internal structure of the image and CImageDecoder requires this to be specified when it is constructed for decodingan image file to a Symbian OS internal bitmap format.

After determiningthe file type you can construct the CImageDecoder instance and startdecoding the image.iImageDecoder = CImageDecoder::FileNewL(iFsSession, aFileName,imageType);iFrameImg = new(ELeave) CFbsBitmap();iFrameImg->Create(iImageDecoder->FrameInfo(0).iOverallSizeInPixels,iImageDecoder->FrameInfo(0).iFrameDisplayMode);iImageDecoder->Convert(&iStatus, *iFrameImg, 0);SetActive();Note that CImageDecoder is asynchronous and requires an activeobject to notify when the image has decoded. After the image is loaded(or if the loading fails), RunL() will be called and you can start using thebitmap image to render it to the screen. Please see the ICL documentationin the Symbian Developer Library (the Multimedia section of the SymbianOS Guide) and the reference documentation for class CFbsBitmap.What may go wrong when you do this: By default, applicationshave 1 MB heap memory to use.

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

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

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

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