Извините, ничего не найдено.

Не расстраивайся! Лучше выпей чайку!
Регистрация
Справка
Календарь

Вернуться   forum.boolean.name > Программирование игр для мобильных телефонов > MidletPascal > Основной форум

Основной форум Сюда все проблемы связанные с программированием.

Ответ
 
Опции темы
Старый 16.06.2008, 00:25   #1
Romanzes
Разработчик
 
Аватар для Romanzes
 
Регистрация: 06.04.2008
Сообщений: 541
Написано 196 полезных сообщений
(для 637 пользователей)
Вопрос 2 вопроса по MP

1. Как выгружать ресурсы из памяти телефона? Я так понимаю, все картинки после того, как они стали не нужны, все равно лежат в памяти и замедляют работу мидлета? Вроде где-то читал, что в java есть функция-чистильщик памяти или что типа этого, но я в джаве не силен
2. Можно ли создавать в MP динамические массивы?
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 00:32   #2
ViNT
Модератор
 
Регистрация: 03.04.2007
Сообщений: 2,252
Написано 597 полезных сообщений
(для 817 пользователей)
Ответ: 2 вопроса по MP

1.Память чистится сама при завершении работы приложения.
2.Стандартных функций нет, если только описывать нужные массивы в отдельной библиотеке, и то, работать с ними как с массивами не удастся.
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 00:52   #3
Romanzes
Разработчик
 
Аватар для Romanzes
 
Регистрация: 06.04.2008
Сообщений: 541
Написано 196 полезных сообщений
(для 637 пользователей)
Ответ: 2 вопроса по MP

я имел в виду чистку памяти во время работы мидлета.
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 02:14   #4
ViNT
Модератор
 
Регистрация: 03.04.2007
Сообщений: 2,252
Написано 597 полезных сообщений
(для 817 пользователей)
Ответ: 2 вопроса по MP

Во время работы скорее всего не получится, в java можно уничтожить объект, приравняв его null, т.е. фактически пустому объекту, в МП это недоступно, функций очистки, как таковых, нет.
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 03:52   #5
odd
Мастер
 
Аватар для odd
 
Регистрация: 06.09.2007
Адрес: Донецк, ДНР
Сообщений: 1,023
Написано 298 полезных сообщений
(для 713 пользователей)
Ответ: 2 вопроса по MP

1. Чистить память пусть косвенно, но можно. Допустим, тебе нужно очистить оперативную память от ненужных картинок img1 и img2. При объявлении переменных сразу объявляешь не 2, а 3 картинки примерно так:

Var img1, img2, spacer: image;

Как известно, картинки нужно же ещё и загружать примерно так:

img1:=LoadImage('/image.png'); img2:=LoadImage('/fon.png');

Заметь, картинка spacer как бы не загружена, то есть фактически она равна null (указывает на несуществующую картику). Тогда для очистки памяти достаточно будет написать пару операторов:

img1:=spacer; img2:=spacer;

И всё. Через какое-то время начнет работать Сборщик Мусора (aka Garbage Collector), он и почистит память от неиспользуемых картинок т.к. они в памяти есть, но ни одна из переменных на них не ссылаются.
Для ускорения вызова Сборщика Мусора нужно вызвать метод gc(). Правда делать это можно только из Java, а из MIDlet Pascal пока никак. Даже дополнительной библиотеки для работы со Сборщиком Мусора я так и не обнаружил. Досадное недоразумение. Может, со временем появится? Писать там строк 5 всего.

Если картинка используется только один раз (например, заставка), то её лучше в переменные и не загружать:

DrawImage(LoadImage('/logo.png'), 0, 0); Repaint; Delay(1000);

2. Можно. Правда пока только для массивов строк. Есть такая библиотека Lib_vdata называется. Там можно добавлять текстовые строки в массив и при этом он будет автоматически расширяться. Очень удобно при чтении названий файлов в какой-нибудь директории когда не знаешь толком сколько же там этих файлов.

Последний раз редактировалось odd, 16.06.2008 в 08:43.
(Offline)
 
Ответить с цитированием
Сообщение было полезно следующим пользователям:
Romanzes (16.06.2008)
Старый 16.06.2008, 12:04   #6
ViNT
Модератор
 
Регистрация: 03.04.2007
Сообщений: 2,252
Написано 597 полезных сообщений
(для 817 пользователей)
Ответ: 2 вопроса по MP

Да, на счет пустой картинки я не подумал.
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 12:39   #7
Romanzes
Разработчик
 
Аватар для Romanzes
 
Регистрация: 06.04.2008
Сообщений: 541
Написано 196 полезных сообщений
(для 637 пользователей)
Ответ: 2 вопроса по MP

odd, спасибо

Посмотрел библиотечку vdata, вроде все понятно.
Возник еще один важный вопрос: есть ли способ представить картинку в виде массива чисел?
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 14:09   #8
ViNT
Модератор
 
Регистрация: 03.04.2007
Сообщений: 2,252
Написано 597 полезных сообщений
(для 817 пользователей)
Ответ: 2 вопроса по MP

Такая функция есть в библиотеке Lib_ui.

Кстати, пробовал очистку ресурсов, результаты не очень обнадеживающие.
Такой код
program imFreeTest;
uses memory;
var
 Im,nil:image;
begin
  drawText(integertostring(memory.free), 0, 0);
  repaint;
  im:=LoadImage('/image.png');
  drawText(integertostring(memory.free), 0, 10);
  repaint;
  Im:=nil;
  drawText(integertostring(memory.free), 0, 20);
  repaint;	
  delay(20000);
end.
дает на SE не очень хорошие результаты:

980096//до заргузки
980032//после загрузки
979744//после "очистки"
Вопрос в том, через какое время сработает "сборщик мусора".
Попробую сделать библиотеку.
К тому же, как я понимаю, при использовании DrawImage(LoadImage('/logo.png'), 0, 0); изображение все равно остается в памяти.

Последний раз редактировалось ViNT, 16.06.2008 в 14:17.
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 14:43   #9
ViNT
Модератор
 
Регистрация: 03.04.2007
Сообщений: 2,252
Написано 597 полезных сообщений
(для 817 пользователей)
Ответ: 2 вопроса по MP

Написал библиотеку.
http://forum.boolean.name/showthread.php?t=6021
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 16:24   #10
Romanzes
Разработчик
 
Аватар для Romanzes
 
Регистрация: 06.04.2008
Сообщений: 541
Написано 196 полезных сообщений
(для 637 пользователей)
Ответ: 2 вопроса по MP

Такая функция есть в библиотеке Lib_ui.
Не нашел
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 17:27   #11
ViNT
Модератор
 
Регистрация: 03.04.2007
Сообщений: 2,252
Написано 597 полезных сообщений
(для 817 пользователей)
Ответ: 2 вопроса по MP

Опять напутал, не в ui, а в Lib_cnv2(get_rgb).
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 18:49   #12
Romanzes
Разработчик
 
Аватар для Romanzes
 
Регистрация: 06.04.2008
Сообщений: 541
Написано 196 полезных сообщений
(для 637 пользователей)
Ответ: 2 вопроса по MP

Теперь вижу. Только не понимаю, как ею пользоваться?
(Offline)
 
Ответить с цитированием
Старый 16.06.2008, 18:53   #13
ViNT
Модератор
 
Регистрация: 03.04.2007
Сообщений: 2,252
Написано 597 полезных сообщений
(для 817 пользователей)
Ответ: 2 вопроса по MP

Сам не пользовался, вот описание:
public void drawRGB(int[] rgbData,
                    int offset,
                    int scanlength,
                    int x,
                    int y,
                    int width,
                    int height,
                    boolean processAlpha)
Renders a series of device-independent RGB+transparency values in a specified region. The values are stored in rgbData in a format with 24 bits of RGB and an eight-bit alpha value (0xAARRGGBB), with the first value stored at the specified offset. The scanlength specifies the relative offset within the array between the corresponding pixels of consecutive rows. Any value for scanlength is acceptable (even negative values) provided that all resulting references are within the bounds of the rgbData array. The ARGB data is rasterized horizontally from left to right within each row. The ARGB values are rendered in the region specified by x, y, width and height, and the operation is subject to the current clip region and translation for this Graphics object. 

Consider P(a,b) to be the value of the pixel located at column a and row b of the Image, where rows and columns are numbered downward from the top starting at zero, and columns are numbered rightward from the left starting at zero. This operation can then be defined as:


    P(a, b) = rgbData[offset + (a - x) + (b - y) * scanlength]       

for 


     x <= a < x + width
     y <= b < y + height    

This capability is provided in the Graphics class so that it can be used to render both to the screen and to offscreen Image objects. The ability to retrieve ARGB values is provided by the Image.getRGB(int[], int, int, int, int, int, int) method. 

If processAlpha is true, the high-order byte of the ARGB format specifies opacity; that is, 0x00RRGGBB specifies a fully transparent pixel and 0xFFRRGGBB specifies a fully opaque pixel. Intermediate alpha values specify semitransparency. If the implementation does not support alpha blending for image rendering operations, it must remove any semitransparency from the source data prior to performing any rendering. (See Alpha Processing for further discussion.) If processAlpha is false, the alpha values are ignored and all pixels must be treated as completely opaque.

The mapping from ARGB values to the device-dependent pixels is platform-specific and may require significant computation.
Parameters:
rgbData - an array of ARGB values in the format 0xAARRGGBB
offset - the array index of the first ARGB value
scanlength - the relative array offset between the corresponding pixels in consecutive rows in the rgbData array
x - the horizontal location of the region to be rendered
y - the vertical location of the region to be rendered
width - the width of the region to be rendered
height - the height of the region to be rendered
processAlpha - true if rgbData has an alpha channel, false if all pixels are fully opaque
===================================================================
public static Image createRGBImage(int[] rgb,
                                   int width,
                                   int height,
                                   boolean processAlpha)
Creates an immutable image from a sequence of ARGB values, specified as 0xAARRGGBB. The ARGB data within the rgb array is arranged horizontally from left to right within each row, row by row from top to bottom. If processAlpha is true, the high-order byte specifies opacity; that is, 0x00RRGGBB specifies a fully transparent pixel and 0xFFRRGGBB specifies a fully opaque pixel. Intermediate alpha values specify semitransparency. If the implementation does not support alpha blending for image rendering operations, it must replace any semitransparent pixels with fully transparent pixels. (See Alpha Processing for further discussion.) If processAlpha is false, the alpha values are ignored and all pixels must be treated as fully opaque. 

Consider P(a,b) to be the value of the pixel located at column a and row b of the Image, where rows and columns are numbered downward from the top starting at zero, and columns are numbered rightward from the left starting at zero. This operation can then be defined as:


    P(a, b) = rgb[a + b * width];    

for


     0 <= a < width
     0 <= b < height    

Parameters:
rgb - an array of ARGB values that composes the image
width - the width of the image
height - the height of the image
processAlpha - true if rgb has an alpha channel, false if all pixels are fully opaque
Returns:
the created image
======================================================================
public void getRGB(int[] rgbData,
                   int offset,
                   int scanlength,
                   int x,
                   int y,
                   int width,
                   int height)
Obtains ARGB pixel data from the specified region of this image and stores it in the provided array of integers. Each pixel value is stored in 0xAARRGGBB format, where the high-order byte contains the alpha channel and the remaining bytes contain color components for red, green and blue, respectively. The alpha channel specifies the opacity of the pixel, where a value of 0x00 represents a pixel that is fully transparent and a value of 0xFF represents a fully opaque pixel. 

The returned values are not guaranteed to be identical to values from the original source, such as from createRGBImage or from a PNG image. Color values may be resampled to reflect the display capabilities of the device (for example, red, green or blue pixels may all be represented by the same gray value on a grayscale device). On devices that do not support alpha blending, the alpha value will be 0xFF for opaque pixels and 0x00 for all other pixels (see Alpha Processing for further discussion.) On devices that support alpha blending, alpha channel values may be resampled to reflect the number of levels of semitransparency supported.

The scanlength specifies the relative offset within the array between the corresponding pixels of consecutive rows. In order to prevent rows of stored pixels from overlapping, the absolute value of scanlength must be greater than or equal to width. Negative values of scanlength are allowed. In all cases, this must result in every reference being within the bounds of the rgbData array.

Consider P(a,b) to be the value of the pixel located at column a and row b of the Image, where rows and columns are numbered downward from the top starting at zero, and columns are numbered rightward from the left starting at zero. This operation can then be defined as:


    rgbData[offset + (a - x) + (b - y) * scanlength] = P(a, b);

for


     x <= a < x + width
     y <= b < y + height    

The source rectangle is required to not exceed the bounds of the image. This means: 


   x >= 0
   y >= 0
   x + width <= image width
   y + height <= image height    

If any of these conditions is not met an IllegalArgumentException is thrown. Otherwise, in cases where width <= 0 or height <= 0, no exception is thrown, and no pixel data is copied to rgbData.
Parameters:
rgbData - an array of integers in which the ARGB pixel data is stored
offset - the index into the array where the first ARGB value is stored
scanlength - the relative offset in the array between corresponding pixels in consecutive rows of the region
x - the x-coordinate of the upper left corner of the region
y - the y-coordinate of the upper left corner of the region
width - the width of the region
height - the height of the region
========================================================================
(Offline)
 
Ответить с цитированием
Сообщение было полезно следующим пользователям:
Romanzes (16.06.2008)
Старый 16.06.2008, 19:35   #14
Romanzes
Разработчик
 
Аватар для Romanzes
 
Регистрация: 06.04.2008
Сообщений: 541
Написано 196 полезных сообщений
(для 637 пользователей)
Ответ: 2 вопроса по MP

Почти как в QBasic'е
(Offline)
 
Ответить с цитированием
Ответ


Опции темы

Ваши права в разделе
Вы не можете создавать темы
Вы не можете отвечать на сообщения
Вы не можете прикреплять файлы
Вы не можете редактировать сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.

Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Два вопроса Andvrok 3D-программирование 25 26.08.2009 16:45
Два небольших вопроса LD 2D-программирование 6 24.05.2009 20:13
Два вопроса по текстурированию neoleg 3D-программирование 16 08.08.2007 19:44
Два вопроса. Stalnoy_Gvozd' 3D Моделирование 7 30.07.2007 21:28


Часовой пояс GMT +4, время: 02:49.


vBulletin® Version 3.6.5.
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Перевод: zCarot
Style crйe par Allan - vBulletin-Ressources.com