If you’re starting learning Qt to develop your next mobile applications, or if you plan to do that (..you should ), you should definitly check out this good tutorial from Forum Nokia: QtWebKit: Beta Labs Example.
Let’s create the FisheyeMenu ActionScript class, that will extend MovieClip, that will be used to implement the actual menu logic:
class FisheyeMenu extends MovieClip
{}
Then, create an empty movie clip in your library, export it, and associate it with the FisheyeMenu class.
Step 2. Initializing the menu
First, define these 4 menu properties, that will hold some useful values:
// focus index of the selected menu item
var focusedIndex:Number;// total number of menu items
var itemsNum:Number;// width of single menu items (in pixels)
var itemWidth:Number;// the MovieClip that will contain the menu items
var itemsContainer:MovieClip;
Let’s also define an utility function that returns the currently focused item index:
public function getFocusedIndex(){returnthis.focusedIndex;}
And then, implement a function that will be used to initialize the menu with the items you want.
public function initializeMenu(itemIds:Array, itemWidth:Number){this.itemsNum= itemIds.length;this.focusedIndex=0;this.itemWidth= itemWidth;this.initItems(itemIds);}private function initItems(itemIds:Array){this.itemsContainer=this.createEmptyMovieClip('itemsContainer', this.getNextHighestDepth());for(var i:Number=0; i < itemIds.length; i++){
var item:MovieClip = itemsContainer.attachMovie(itemIds[i], 'item_'+ i, itemsContainer.getNextHighestDepth(), {_x: itemWidth * i, _y:0});if(i >0){
item._xscale =50;
item._yscale =50;}}}
The initializeMenu() function is the function you will call to initialize your fisheye menu with the items you want. Its arguments are:
an Array containing the id of MovieClip symbols to be used as items
the width of single menu items
Once called, initializeMenu()initializes the menu properties and then calls the initItems() function, that will actually attach the item instances, scaling down the unselected items and translating the menu itself to its starting position.
The getMenuLeft() function returns the x position to be used for the itemsContainerMovieClip, and depends on the focused item index:
private function getMenuLeft():Number{return- itemWidth * focusedIndex;}
Step 3. Implement sliding funcionality
When the user presses LEFT and RIGHT keys, you want the menu to perform these steps:
change the focused item, scaling down the previously focused one, and scaling up the new
translate the menu to be centered on the new focused item
In ActionScript, you can do it this way:
public function shiftItem(itemDelta:Number){
var nextIndex:Number= focusedIndex + itemDelta;if(nextIndex >=0&& nextIndex < itemsNum){
scaleItem(focusedIndex, true);
focusedIndex = nextIndex;
scaleItem(focusedIndex, false);
moveMenu();}}private function moveMenu():Void{new Tween(itemsContainer, "_x", None.easeNone, itemsContainer._x, getMenuLeft(), .50, true);}private function scaleItem(itemIndex:Number, scaleDown:Boolean):Void{
var item:MovieClip = itemsContainer['item_'+ itemIndex];
var fromScale:Number= scaleDown ?100:50;
var toScale:Number= scaleDown ?50:100;new Tween(item, "_xscale", None.easeNone, fromScale, toScale, .50, true);new Tween(item, "_yscale", None.easeNone, fromScale, toScale, .50, true);}
In this code snippet, there are 3 functions:
shiftItem() is the function called to change the focused Item index by the passed delta argument. It checks if the change is ok, and then calls the following 2 functions:
moveMenu() actually translates the items container, to have the new focused item horizontally centered
scaleItem()scales up or down, depending on the scaleDown argument, the item corresponding at the index passed as argument
Since here we use the Tween class, we have to add these 2 import lines at the beginning of the ActionScript file:
Take back your FLA, and create 3 symbols that will be used as items within the fisheye menu. Also, remember to check the “Export for ActionScript” option, to have them actually usable from ActionScript itself.
Step 5. Attach and initialize the menu
Now, attach a FisheyeMenu istance directly to the _root, and initialize it with the ID of the symbols created in the previous step:
var menu:MovieClip = _root.attachMovie('FisheyeMenu', 'main_menu', _root.getNextHighestDepth());
var items:Array=newArray('Item0', 'Item1', 'Item2');
menu._x =120;
menu._y =120;
menu.initializeMenu(items, 50);
Step 6. Create a KeyListener to interact with the menu
The KeyListener will be really simple, since it will simply call the shiftItem() function when the user press LEFT or RIGHT keys, and will call a custom function when the user press the ENTER key, to trace the index of the current focused item:
var keyListener:Object=newObject();
keyListener.onKeyDown= function(){
var key:Number=Key.getCode();if(key ==Key.RIGHT){
menu.shiftItem(1);}elseif(key ==Key.LEFT){
menu.shiftItem(-1);}elseif(key ==Key.ENTER){
menuFireAction();}}Key.addListener(keyListener);
function menuFireAction(){
trace("MENU ITEM PRESSED: "+ menu.getFocusedIndex());}
Downloads and related resources
You can download full source code (FLA + ActionScript file) of this example here:
publicstaticImage createReflectedImage(Image image, int bgColor, int reflectionHeight){}
We have 3 arguments:
the original image that we want to reflect
the background color (used for transparent images)
the height of the reflection effect
2. The mutable Image
Now, let’s create the mutable Image that will hold the resulting effect:
int w = image.getWidth();int h = image.getHeight();Image reflectedImage =Image.createImage(w, h + reflectionHeight);
We store the original image width and height into 2 int variables, and then create the mutable image with the same width, but with an height equal to h (the original image) plus the specified reflection height.
3. Copy the original Image
Now, first drawing steps are:
Getting the Graphics object of our mutable image
Filling the image with the background color
Drawing the original image on the upper part of the mutable one
Graphics g = reflectedImage.getGraphics();
g.setColor(bgColor);
g.fillRect(0, 0, w, h + reflectionHeight);
g.drawImage(image, 0, 0, Graphics.TOP|Graphics.LEFT);
4. Create the reflection effect
Now, let’s get to the important part of this tutorial, that is the reflection effect itself:
for each horizontal line of the reflected image part, take the corresponding vertical coordinate of the original image
get the RGBA data of the corresponding horizontal line of the original image
calculate the alpha to be applied to this line, and apply it to each element of the RGB data array
draw the RGB data into the reflected image, by using its Graphics object
And here is the source code:
int[] rgba =newint[w];int currentY =-1;for(int i =0; i < reflectionHeight; i++){int y =(h -1)-(i * h / reflectionHeight);if(y != currentY)
image.getRGB(rgba, 0, w, 0, y, w, 1);int alpha = 0xff -(i * 0xff / reflectionHeight);for(int j =0; j < w; j++){int origAlpha =(rgba[j]>>24);int newAlpha =(alpha & origAlpha)* alpha / 0xff;
rgba[j]=(rgba[j]& 0x00ffffff);
rgba[j]=(rgba[j]|(newAlpha <<24));}
g.drawRGB(rgba, 0, w, 0, h + i, w, 1, true);}
as you can see, the rgba[]int array holds the current pixel row data, and will be refreshed only when necessary (so, when the y coordinate of the original image changes).
Sample usage
Using the above method is really simple, since it’s only necessary to:
Create the original Image
CallcreateReflectedImage() method by passing the original Image as argument, together with the background color and the reflection effect height
Now, here are some internal properties, that will be used to handle list items content and positioning.
// will contain item splitted linesString[][] itemLines =null;// will hold items image partsImage[] images =null;// will hold selected item indexpublicint selectedItem =0;// these will hold item graphical propertiesint[] itemsTop =null;int[] itemsHeight =null;// these will hold List vertical scrollingint scrollTop =0;finalint SCROLL_STEP =40;
Now, here is the CanvasList constructor. Its arguments are (similarly to javax.microedition.lcdui.List constructor):
the screen’s title
set of strings specifying the string parts of the List elements
set of images specifying the image parts of the List elements
This article will not cover the handling of different types of Lists (e.g.: exclusive, multiple, ..).
public CanvasList(String title, String[] items, Image[] imageElements){
setTitle(title);this.images= imageElements;
itemLines =newString[items.length][];
itemsTop =newint[itemLines.length];
itemsHeight =newint[itemLines.length];for(int i =0; i < itemLines.length; i++){// get image part of this item, if availableImage imagePart = getImage(i);// get avaiable width for textint w = getItemWidth()-(imagePart !=null? imagePart.getWidth()+ padding :0);// and split item text into text rows, to fit available width
itemLines[i]= getTextRows((String) items[i], font, w);}}
Here are the 2 utility methods found in the CanvasList constructor:
protectedvoid paint(Graphics g){// paint List background
g.setColor(bgColor);
g.fillRect(0, 0, getWidth(), getHeight());// translate accordingly to current List vertical scroll
g.translate(0, - scrollTop);int top =0;
g.setFont(font);// loop List itemsfor(int i =0; i < itemLines.length; i++){int itemRows = itemLines[i].length;Image imagePart = getImage(i);int itemHeight = itemRows * font.getHeight()+ linePadding *(itemRows -1);
itemsTop[i]= top;
itemsHeight[i]= itemHeight;// is image part higher than the text part?if(imagePart !=null&& imagePart.getHeight()> itemHeight){
itemHeight = imagePart.getHeight();}
itemHeight +=2* padding +2* borderWidth;
g.translate(0, top);if(borderWidth >0){// paint item border
g.setColor(i == selectedItem ? borderSelectedColor : borderColor);
g.fillRect(margin, margin, getWidth()-2* margin, itemHeight);}// paint item background
g.setColor(i == selectedItem ? backSelectedColor : backColor);
g.fillRect(margin + borderWidth, margin + borderWidth, getWidth()-2* margin -2* borderWidth, itemHeight -2* borderWidth);// has this item an image part?if(imagePart !=null){
g.drawImage(imagePart, margin + borderWidth + padding, margin + borderWidth + padding, Graphics.TOP|Graphics.LEFT);}// paint item text rows
g.setColor(i == selectedItem ? foreSelectedColor : foreColor);int textLeft = margin + borderWidth + padding +(imagePart !=null? imagePart.getWidth()+ padding :0);for(int j =0; j < itemRows; j++){
g.drawString(itemLines[i][j], textLeft, margin + borderWidth + padding + j *(linePadding + font.getHeight()), Graphics.TOP|Graphics.LEFT);}
g.translate(0, - top);
top += itemHeight +2* margin;}// finally, translate back
g.translate(0, scrollTop);}
And finally, to handle user key events, here is the keyPressed() event:
protectedvoid keyPressed(int key){int keyCode = getGameAction(key);// is there 1 item at least?if(itemLines.length>0){// going upif(keyCode ==Canvas.UP){// current item is clipped on top, so can scroll upif(itemsTop[selectedItem]< scrollTop){
scrollTop -= SCROLL_STEP;
repaint();}// is there a previous item?elseif(selectedItem >0){
selectedItem--;
repaint();}}//going downelseif(keyCode ==Canvas.DOWN){// current item is clipped on bottom, so can scroll downif(itemsTop[selectedItem]+ itemsHeight[selectedItem]>= scrollTop + getHeight()){
scrollTop += SCROLL_STEP;
repaint();}// is there a following item?elseif(selectedItem < itemLines.length-1){
selectedItem++;
repaint();}}}}
About the getTextRows() method, you can grab an implementation (but you could find a lot of other ones on the Web) on this other article written some time ago: J2ME Scrollable Text.
How to use CanvasList class
Here is a sample usage of CanvasList class, that will display a list (without image parts):
Very good tutorial about scrollable list view, it meets my demand. But the getTextRows() method has some shortcoming: it does not support language not using space as delimiter, like Chinese and Japanese.
But I am phasing the problem in converting the same for touch. As we need to give touch scrolling on the list. This post is for keypress events. can you please provide the same with touch scrolling.
Reply