Модераторы: javastic, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Бегущая строка в Canvas, Если строка выходит за пределы 
V
    Опции темы
Цербер
Дата 3.9.2009, 09:42 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 333
Регистрация: 21.11.2007

Репутация: 1
Всего: 1



Доброго времени суток уважаемые форумчане!
Помогите реализовать бегущую строку в Canvas, т.е. если строка выходит за пределы делать её бегущей.
Логически я себе представляю как это сделать. 
узнать длину строки - готово str.length(), 
обозначить width одного символа
substring-ом резать строку с итеррацией начала и конца строки,
и рисовать новую строку через n-ое число секунд или мсек. 
Вот только заморочка имено в таймауте. в javascript-е есть функция таймаут запускает функцию через n-ое кол-во мсек, а в Java я не нашёл аналога, только Thread но как всё это вместе заюзать не понял. Надеюсь на вашу помощь!
PM MAIL ICQ   Вверх
hamsterKSU
Дата 3.9.2009, 10:44 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 401
Регистрация: 20.10.2006
Где: Украина, Херсон

Репутация: 7
Всего: 11



ну вот видишь все сам знаешь - надо только написать.

вот ссылка для размышлений - http://java.sun.com/javame/reference/apis/jsr118/

P.S. на форуме могут подсказать, помочь найти/исправить ошибку, но никто не будет делать за вас что-то. Проявите инициативу smile

Добавлено через 1 минуту и 58 секунд
могу подсказать еще такую штуку:
Заводишь один паток для всех лейблов, там держишь список леблов на скрине.
обходишь их постоянно и если надо перерисовываешь через некорый интервал.
PM MAIL ICQ   Вверх
Цербер
Дата 3.9.2009, 11:16 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 333
Регистрация: 21.11.2007

Репутация: 1
Всего: 1



hamsterKSU я просто хотел посмотреть пример кода с применением тайм аута=) как его использовать наглядно. smile 
буду пробовать =) как что то доведу до более менее разумного выложу код. но думаю вопросы ещё будут!

PM MAIL ICQ   Вверх
eugine_s
Дата 3.9.2009, 12:22 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 581
Регистрация: 14.11.2007
Где: Киев

Репутация: 17
Всего: 17



Цербер, а как у тебя экран отрисовывается? По событию или постоянно обновляется (с каким-то тайм-аутом)? 
PM MAIL   Вверх
Цербер
Дата 3.9.2009, 13:00 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 333
Регистрация: 21.11.2007

Репутация: 1
Всего: 1



eugine_s при событии, вниз вверх и отрисовывается менюшка выделяющая выбранный элемент, я ща хочу сделать что бы этот элемент был как бегущая строка!
PM MAIL ICQ   Вверх
Цербер
Дата 3.9.2009, 15:30 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 333
Регистрация: 21.11.2007

Репутация: 1
Всего: 1



Ну вот начитался, насмотрелся примеров, сделал - работает!
Но есть одно но.
Я создал отдельный проект с мидлетом и там всё работает а вот уже в другой проект пытаюсь внедрить, но что то не получается=(
может взгляните??
вот код класса бегущей строки:

Код

package tcity;

import javax.microedition.lcdui.*;

public class RunStr extends Canvas implements Runnable{

    private boolean mTrucking;
    private boolean direction = true;
    private int begin = 0;
    private int end;
    private int oneChar = 5;
    private int countChars;
    private int mDelay = 200;
    private int x;
    private int y;
    private int hStr;
    private String label;
    private int sizeStr;

    RunStr(String str, int xConstructor, int yConstructor, int hStrConstructor) {
        sizeStr = str.length();
        label = str;
        x = xConstructor;
        y = yConstructor;
        hStr = hStrConstructor;
    }

    public void start() {
        mTrucking = true;
        Thread t = new Thread(this);
        t.start();
    }

    public void stop() {
        mTrucking = false;
    }

    public void paint(Graphics g) {
        int width = getWidth();
        countChars = width/oneChar;
        end = begin + countChars;
        String substr = label.substring(begin, end);
        g.setColor(0x83c124);
        g.fillRect(0, y,  width, hStr);
        g.setColor(0x3e4345);
        g.drawString(substr, x, y, Graphics.TOP | Graphics.LEFT);
    }

    public void run() {
        while (mTrucking) {
            if(begin==0) {
                direction = true;
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException ie) {
                    System.out.println(ie.getMessage());
                }
            }
            if(end == sizeStr) {
                direction = false;
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException ie) {
                    System.out.println(ie.getMessage());
                }
            }
            if(direction == false) {
                begin  -=1;
            }
            if (direction == true) {
                begin +=1;
            }
            repaint();
            try {
                Thread.sleep(mDelay);
            }
            catch (InterruptedException ie) {
                System.out.println(ie.getMessage());
            }
        }
    }


}



а вот класс куда я его пытаюсь внедрить:

Код

package tcity;

import javax.microedition.lcdui.*;

public class DrawList extends Canvas implements CommandListener {

    private int index = 0;
    private int hStr = 20;
    private int indexOff = 0;
    private int displayCount = 0;
    private int topPadding = 0;
    private String titleList;
    
    private String str[] = { 
            "Одежда, обувь, аксессуары. Одежда, обувь, аксессуары", "Сельское хозяйство, садоводство. Сельское хозяйство, садоводство", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
            "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34",
            "35", "36", "37", "38", "39"
    };

    public DrawList(String title) {
        titleList = title;
        displayCount = (getHeight() - hStr) / hStr;

        topPadding = ((getHeight()) % hStr) / 2;
    }
    public void paint(Graphics g) {
        drawBackground(g);
        int yPosStr = topPadding;
        g.setColor(0x3b4443);
        g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM));
        g.drawString(titleList, getWidth()/2, 2, Graphics.TOP | Graphics.HCENTER);
        for (int i = indexOff; i < indexOff + displayCount && i < str.length; i++) {
            if (i == index) {
                
                
                drawSelectedLabel(g, 0, yPosStr + hStr, str[i],5);
            } else {
                drawLabel(g, 0, yPosStr + hStr, str[i], 5);
            }
            yPosStr += hStr;
        }
        if(isScroolNeed())
            VerticalScrollBar.paintVerticalScrollbar(g, 0, topPadding + hStr, g.getClipWidth(), (g.getClipHeight() - 2 * topPadding) - hStr, indexOff * hStr, str.length * hStr);
    }

    private void drawBackground(Graphics g) {
        int width = g.getClipWidth();
        int height = g.getClipHeight();
        g.setColor(255, 255, 255);
        g.fillRect(0, 0, width, height);
    }

    /**
     *
     * @param g
     * @param x
     * @param y
     * @param label
     * @param padding -
     *            отступ текста
     * @param margin -
     *            отступ от края экрана
     */
    private void drawSelectedLabel(Graphics g, int x, int y, String label, int margin) {
        x += margin;
        g.setColor(0x83c124);
        int width = g.getClipWidth();
        if(isScroolNeed()){
            width -= VerticalScrollBar.SCROLL_WIDTH;
        }
        /*g.fillRect(0, y,  width, hStr);
        g.setColor(0x3e4345);
        g.drawString(label, x, y, Graphics.TOP | Graphics.LEFT);*/
        RunStr r = new RunStr(label, 0, y, hStr);
        r.start();

    }

    private void drawLabel(Graphics g, int x, int y, String label, int margin) {
        g.setColor(0x3e4345);
        g.drawString(label, x + margin, y, Graphics.TOP | Graphics.LEFT);
    }

    
    /*
     * public void drawScroll(Graphics g, int borderClr, int barCrl, int
     * scrollClr, int yPosScrl) { g.setColor(borderClr); g.drawRect(width - 8,
     * 0, width, height); g.setColor(barCrl); g.fillRect(width - 7, 0, width,
     * height); g.setColor(scrollClr); g.fillRect(width - 7, yPosScroll, width,
     * hScroll); }
     */

    public void keyPressed(int keyCode) {
        int action = getGameAction(keyCode); // Заносим в переменную код
        // нажатой
        // кнопки
        switch (action) {
        case Canvas.DOWN:
            moveDown();
            break;
        case Canvas.UP:
            moveUp();
            break;
        case Canvas.FIRE:
            // Tcity.getInstance().showKey(index);
            break;
        }
    }

    protected void keyRepeated(int keyCode) {// если держат нажатой кнопку.
        int action = getGameAction(keyCode);
        switch (action) {
        case Canvas.DOWN:
            moveDown();
            break;
        case Canvas.UP:
            moveUp();
            break;
        }
    }

    public void commandAction(Command c, Displayable d) {

    }

    private void moveUp() {
        if (index == 0) {
            indexOff = str.length - displayCount;
            index = str.length - 1;
        } else {
            if (index == indexOff) {
                indexOff--;
            }
            index--;
        }
        repaint();
    }

    private void moveDown() {
        if (index == str.length - 1) {
            indexOff = 0;
            index = 0;
        } else {
            if (index == indexOff + displayCount - 1) {
                indexOff++;
            }
            index++;
        }
        repaint();
    }

    private boolean isScroolNeed(){
        return str.length > displayCount;
    }

    private static class VerticalScrollBar {

        public static final int SCROLL_WIDTH = 4;

        private static final int SCROLL_BORDER_COLOR = 0x15d015;

        private static final int SCROLL_BG_COLOR = 0x3b4443;

        private static final int SCROLL_TRACKBAR_COLOR = 0xc4cccb;

        public static void paintVerticalScrollbar(Graphics g, int x, int y, int width, int height, int offset, int formHeight) {
            // Make the scrollbar as wide as the rounding diameter.
            int left = x + width - SCROLL_WIDTH;
            // Draw the scrollbar background.
            paintScrollbarBackground(g, left, y, SCROLL_WIDTH, height+1);
            // Draw an edge to the scrollbar.
            g.setColor(SCROLL_BORDER_COLOR);
            g.drawLine(left-1, y, left-1, y + height);
            

            // Calculate the height of the trackbar.
            int scrollableHeight = formHeight - height;
            double trackbarPercentage = (double) height / (double) formHeight;
            int trackbarHeight = round((height * trackbarPercentage) / 2);
            trackbarHeight = Math.max(trackbarHeight, 2 * SCROLL_WIDTH);

            // Calculate the range and location of the trackbar.
            // The scrollbar doesn't actually go from 0% to 100%. The top
            // is actually 1/2 the height of the trackbar from the top of
            // the screen. The bottom is 1/2 the height from the bottom.
            int rangeStart = trackbarHeight / 2;
            int range = height - 2 * rangeStart;

            double offsetPercentage = (double) offset / (double) scrollableHeight;
            int center = y + rangeStart + round(offsetPercentage * range);

            // Draw the trackbar.
            paintTrackbar(g, left, center - rangeStart, SCROLL_WIDTH+2, trackbarHeight);
        }

        protected static void paintTrackbar(Graphics g, int x, int y, int width, int height) {
            // This code would paint the scrollbar a solid background.
            g.setColor(SCROLL_TRACKBAR_COLOR);
            g.fillRect(x, y, width, height);
        }

        protected static void paintScrollbarBackground(Graphics g, int x, int y, int width, int height) {
            g.setColor(SCROLL_BG_COLOR);
            g.fillRect(x, y, width, height);
        }

        public static int round(double a) {
            return (int) Math.floor(a + 0.5);
        }
        
    }
}

PM MAIL ICQ   Вверх
hamsterKSU
Дата 3.9.2009, 15:34 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 401
Регистрация: 20.10.2006
Где: Украина, Херсон

Репутация: 7
Всего: 11



ага... вот это у же что-то .
делай  DrawList как в RunStr
там надо поменять всего метод drawSelectedLabel

если не получиться - помогу сделать
PM MAIL ICQ   Вверх
Цербер
Дата 3.9.2009, 15:40 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 333
Регистрация: 21.11.2007

Репутация: 1
Всего: 1



hamsterKSU а что конкретно переделать в drawSelectedLabel ??


Цитата

делай  DrawList как в RunStr

методы перетащить в DrawList ?? а что делать с методом paint? 

наверно я тя не правильно понимаю =(
PM MAIL ICQ   Вверх
hamsterKSU
Дата 3.9.2009, 16:28 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 401
Регистрация: 20.10.2006
Где: Украина, Херсон

Репутация: 7
Всего: 11



держи
Код

import javax.microedition.lcdui.*;

public class DrawList extends Canvas implements CommandListener, Runnable {

    private Thread drawThread = new Thread(this); 
    
    private int index = 0;
    private int hStr = 20;
    private int indexOff = 0;
    private int displayCount = 0;
    private int topPadding = 0;
    private String titleList;
    
    private String str[] = { 
            "Одежда, обувь, аксессуары. Одежда, обувь, аксессуары", "Сельское хозяйство, садоводство. Сельское хозяйство, садоводство", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
            "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34",
            "35", "36", "37", "38", "39"
    };

    public DrawList(String title) {
        titleList = title;
        displayCount = (getHeight() - hStr) / hStr;
        topPadding = ((getHeight()) % hStr) / 2;
        drawThread.start();
    }
    
    public void paint(Graphics g) {
        drawBackground(g);
        int yPosStr = topPadding;
        g.setColor(0x3b4443);
        g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM));
        g.drawString(titleList, getWidth()/2, 2, Graphics.TOP | Graphics.HCENTER);
        for (int i = indexOff; i < indexOff + displayCount && i < str.length; i++) {
            if (i == index) {
                
                
                drawSelectedLabel(g, 0, yPosStr + hStr, str[i],5);
            } else {
                drawLabel(g, 0, yPosStr + hStr, str[i], 5);
            }
            yPosStr += hStr;
        }
        if(isScroolNeed())
            VerticalScrollBar.paintVerticalScrollbar(g, 0, topPadding + hStr, g.getClipWidth(), (g.getClipHeight() - 2 * topPadding) - hStr, indexOff * hStr, str.length * hStr);
    }

    private void drawBackground(Graphics g) {
        int width = g.getClipWidth();
        int height = g.getClipHeight();
        g.setColor(255, 255, 255);
        g.fillRect(0, 0, width, height);
    }

    /**
     *
     * @param g
     * @param x
     * @param y
     * @param label
     * @param padding -
     *            отступ текста
     * @param margin -
     *            отступ от края экрана
     */
    private void drawSelectedLabel(Graphics g, int x, int y, String label, int margin) {
        x += margin;
        g.setColor(0x83c124);
        int width = g.getClipWidth();
        if(isScroolNeed()){
            width -= VerticalScrollBar.SCROLL_WIDTH;
        }
        g.fillRect(0, y,  width, hStr);
        g.setColor(0x3e4345);
        
        int chWidth = g.getFont().charWidth('a');
        int countChars = width/chWidth;
        if(label.length() < countChars){
         g.drawString(label, x, y, Graphics.TOP | Graphics.LEFT);
        }else{
         int endLabelDrawIndex = startLabelDrawIndex + countChars;
            if(endLabelDrawIndex > label.length() - 1){
             endLabelDrawIndex = label.length() - 1;
            }
            String substr = label;
            if(endLabelDrawIndex != 0)
             substr = label.substring(startLabelDrawIndex, endLabelDrawIndex);
            g.drawString(substr, x, y, Graphics.TOP | Graphics.LEFT);
            if(substr.length() < label.length() && substr.length() < countChars){
             substr = label.substring(0, countChars - substr.length() - 1);
             g.drawString(substr, getWidth() + margin, y, Graphics.TOP | Graphics.RIGHT);
            }
        }
    }
    
    private int startLabelDrawIndex = 0;
    
    private void drawLabel(Graphics g, int x, int y, String label, int margin) {
        g.setColor(0x3e4345);
        g.drawString(label, x + margin, y, Graphics.TOP | Graphics.LEFT);
    }

    public void keyPressed(int keyCode) {
        int action = getGameAction(keyCode); // Заносим в переменную код
        // нажатой
        // кнопки
        switch (action) {
        case Canvas.DOWN:
            moveDown();
            break;
        case Canvas.UP:
            moveUp();
            break;
        case Canvas.FIRE:
            // Tcity.getInstance().showKey(index);
            break;
        }
    }

    protected void keyRepeated(int keyCode) {// если держат нажатой кнопку.
        int action = getGameAction(keyCode);
        switch (action) {
        case Canvas.DOWN:
            moveDown();
            break;
        case Canvas.UP:
            moveUp();
            break;
        }
    }

    public void commandAction(Command c, Displayable d) {
     isRunned = false;
     
    }

    private void moveUp() {
        if (index == 0) {
            indexOff = str.length - displayCount;
            index = str.length - 1;
        } else {
            if (index == indexOff) {
                indexOff--;
            }
            index--;
        }
        startLabelDrawIndex = 0;
        repaint();
    }

    private void moveDown() {
        if (index == str.length - 1) {
            indexOff = 0;
            index = 0;
        } else {
            if (index == indexOff + displayCount - 1) {
                indexOff++;
            }
            index++;
        }
        startLabelDrawIndex = 0;
        repaint();
    }

    private boolean isScroolNeed(){
        return str.length > displayCount;
    }

    private static class VerticalScrollBar {

        public static final int SCROLL_WIDTH = 4;

        private static final int SCROLL_BORDER_COLOR = 0x15d015;

        private static final int SCROLL_BG_COLOR = 0x3b4443;

        private static final int SCROLL_TRACKBAR_COLOR = 0xc4cccb;

        public static void paintVerticalScrollbar(Graphics g, int x, int y, int width, int height, int offset, int formHeight) {
            // Make the scrollbar as wide as the rounding diameter.
            int left = x + width - SCROLL_WIDTH;
            // Draw the scrollbar background.
            paintScrollbarBackground(g, left, y, SCROLL_WIDTH, height+1);
            // Draw an edge to the scrollbar.
            g.setColor(SCROLL_BORDER_COLOR);
            g.drawLine(left-1, y, left-1, y + height);
            

            // Calculate the height of the trackbar.
            int scrollableHeight = formHeight - height;
            double trackbarPercentage = (double) height / (double) formHeight;
            int trackbarHeight = round((height * trackbarPercentage) / 2);
            trackbarHeight = Math.max(trackbarHeight, 2 * SCROLL_WIDTH);

            // Calculate the range and location of the trackbar.
            // The scrollbar doesn't actually go from 0% to 100%. The top
            // is actually 1/2 the height of the trackbar from the top of
            // the screen. The bottom is 1/2 the height from the bottom.
            int rangeStart = trackbarHeight / 2;
            int range = height - 2 * rangeStart;

            double offsetPercentage = (double) offset / (double) scrollableHeight;
            int center = y + rangeStart + round(offsetPercentage * range);

            // Draw the trackbar.
            paintTrackbar(g, left, center - rangeStart, SCROLL_WIDTH+2, trackbarHeight);
        }

        protected static void paintTrackbar(Graphics g, int x, int y, int width, int height) {
            // This code would paint the scrollbar a solid background.
            g.setColor(SCROLL_TRACKBAR_COLOR);
            g.fillRect(x, y, width, height);
        }

        protected static void paintScrollbarBackground(Graphics g, int x, int y, int width, int height) {
            g.setColor(SCROLL_BG_COLOR);
            g.fillRect(x, y, width, height);
        }

        public static int round(double a) {
            return (int) Math.floor(a + 0.5);
        }
        
    }

    private boolean isRunned = true;
    public void run() {
        while (isRunned) {
            startLabelDrawIndex++;
            if(startLabelDrawIndex < 0 || startLabelDrawIndex > str[index].length() - 1)
             startLabelDrawIndex = 0;
            repaint();
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException ie) {
                System.out.println(ie.getMessage());
            }
        }
    }
}


Добавлено @ 16:29
надпись вращаеться по кругу, вроде. Проверишь

и отвыкай делать глобальные переменные и зашивать размеры константами - все можно высчитать. 

Это сообщение отредактировал(а) hamsterKSU - 3.9.2009, 16:32
PM MAIL ICQ   Вверх
Цербер
Дата 3.9.2009, 17:03 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 333
Регистрация: 21.11.2007

Репутация: 1
Всего: 1



hamsterKSU спасибо друг! опять выручил smile  
полез ковыряться в коде!!
 
Цитата

и отвыкай делать глобальные переменные и зашивать размеры константами - все можно высчитать. 

буду стараться =)

Это сообщение отредактировал(а) Цербер - 3.9.2009, 17:04
PM MAIL ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса

  • Прежде чем задать вопрос прочтите это!
  • Литература по Java находится здесь.
  • Литературу по Java обсуждаем здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит" (возле кнопок кодов) если у Вас нет русских шрифтов.
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда

  • FAQ раздела лежит здесь!
 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java ME (J2ME) | Следующая тема »


 




[ Время генерации скрипта: 0.0612 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.