simple custom scroll in flash

Upload: damai-trekkerz

Post on 07-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Simple Custom Scroll in Flash

    1/18

    Simple Custom Scrollbar

    Scrollbars are great for displaying a lot of information within a small area. Despite their importance, weoften take scrollbars for granted. For example, your browser window should display a scrollbar on the

    right side of this page for allowing you to easily scroll down. We don't really think about them;- we justexpect them to be there when the need arises.Yet, creating a scrollbar is trickier than using one. In this tutorial, you will learn how to create your owncompact, easily customizable scrollbar in Flash. Even though Flash comes with several scrollingcomponents, the scrollbar you will be creating allows for easier customization along with a significantlysmaller file size compared to its built-in variation.

    Creating a Scrollbar:

    i. Okay, lets get started by downloading the provided incomplete source below. Don't worry, thepartial source only contains the content that you will be scrolling:

    ii. Once you unzip and open the scrollerIncomplete.fla file, all you should see is a large movie clipcontaining some text and images. Select the movie clip and give it the instancename contentMain:

    [ give your content movie clip the instance name contentMain ]

    iii. Now, we need to create a mask that will only display the portion of the content we would like tosee. Insert a new layer and call it mask.

    iv. Make sure your newly created mask layer is selected. On the stage, draw a medium sizedsquare. Select your square, and enter the following values in the Properties panel for the square:

    i. Width: 300

    ii. Height: 200

    iii. X: 0

    iv. Y: 0

    You are basically creating a 300x200 rectangle that covers up your entire drawing area. YourProperties panels should look similar to the following image:

  • 8/6/2019 Simple Custom Scroll in Flash

    2/18

    [ ensure your rectangle is 300x200 with a x/y offset of 0 ]

    v. Select your rectangle and press F8 (Modify | Convert to Symbol). Select the option for Movie Clipand press OK.

    vi. With your rectangle converted to a movie clip, let's give it an instance name. Ensure the newlyconverted movie clip is selected. In the Properties panel, give it the instance name maskedView:

    vii. With your rectangle created and properly sized, right click on your mask layer and select Mask.You will notice that your contentMain movie clip only takes up the space filled by your rectangle:

    [ your content is no longer overflowing from the stage; it is masked ]

    On the next page, you will add the scroll track and the scroll face (dragger). You'll have a fully functioning

    scrollbar in no time!

  • 8/6/2019 Simple Custom Scroll in Flash

    3/18

    In the previous page, you masked the content so that your users do not see everything at once. In thispage, you will create the scrollbar and related accessories that will allow you to scroll through the contenteasily.

    Let's pick up from where we left off:

    viii. Create a new layer and call it scrolltrack. Ensure that you have selected this layer.

    ix. Draw a tall rectangle without a border. For the fill color, give it any lightly-colored background. Tobe more accurate with the size, let's enter the width, height, and x/y offsets using the Propertiespanel.

    Select your newly drawn rectangle and enter the following values into your Properties panel:

    i. Width: 20

    ii. Height: 160

    iii. X: 280

    iv. Y: 0

    Your rectangle should now be placed on the right side of your movie:

    [ your rectangle is located on the right side of your movie ]

    x. Select your rectangle again. Press F8 (Modify | Convert to Symbol). The Convert to Symboldialog window should appear. Give it the name scrolltrack, select the option for Movie Clip, andthen press OK:

  • 8/6/2019 Simple Custom Scroll in Flash

    4/18

    [ convert your rectangle to movie clip ]

    xi. With your rectangle now a movie clip, let's give it an instance name. Select the scrolltrack movieclip (formerly the tall rectangle) and give it the instance namescrollTrack from the Propertiespanel

    [ give your newly converted movie clip the instance name scrollTrack ]

    xii. Let's add our scrollFace (the thing you click and drag) now. Create a new layer, and give it thename scrollface.

    xiii. With your scrollface layer selected, draw a small rectangle on your stage. Give it a darker fill colorthan your scrollTrack rectangle. Select your rectangle, and in the Properties panel, enter thefollowing values:

    i. Width: 20

    ii. Height: 40

    iii. X: 280

    iv. Y: 100

    Your rectangle should look similar to the following:

    [ the rectangle that will eventually become your scroll face ]

    xiv. Let's now turn the square into a movieclip. Select the square, press F8 or go to Modify | Convert

    to Symbol. Give it a name such as scrollface, select the option for Movie Clip, and press OK.

    xv. Now, select your rectangle (now a movie clip), and give it the instance namescrollFace:

  • 8/6/2019 Simple Custom Scroll in Flash

    5/18

    [ give the scrollface movie clip the instance name scrollFace ]

    On the next page, let's add our up and down buttons and add our code!

    On the previous page, you added the scroll track and scroll face. Let's finish up the interface on this pageby adding our up and down buttons. I will also provide the code needed to get everything working.

    Let's continue from the previous page:

    xi. Create another new layer and give it the label buttons.

    xii. Draw two squares with each square having a width and heightof20 pixels. The squares willrepresent the up and down buttons for the scrollbar.

    xiii. Now, draw an up arrow on one square and a down arrow on another. I simply draw a small v andan upside down small v instead:

    xiv. We need to convert each of these squares into button movie clips. Select one square (and itsarrow) and press F8 (Modify | Convert to Symbol). From the Convert to Symbol Dialog window,select the option forMovie Clip and press OK.

    xv. Repeat the same process as Step xiv for your other, unconverted square. In the end, both of yoursquares should be movie clips.

    xvi. Select the movie clip with the up arrow. In the Properties panel, enter the following values for Xand Y:

    i. X: 280

    ii. Y: 0

  • 8/6/2019 Simple Custom Scroll in Flash

    6/18

    Now, select your movie clip with the down arrow. Enter the following X and Y values for it in theProperties panel:

    i. X: 280

    ii. Y: 180

    Your interface should look like the following image:

    xvii. We aren't done with the interface quite yet. Select your up movie clip and give it the instancename: btnUp. Likewise, select your down movie clip and give it the instance name: btnDown.

    xviii. Now, we are done with our interface! Let's add some code. Create a new layer and labelit actions. Right click on the first (and only) frame on that layer and select Actions. Copy andpaste the following code into your Actions panel:

    xix. Test your movie by either previewing it in the browser by pressing F12 or preview the file in Flash

    by pressing Ctrl + Enter. You now have a fully functioning scrollbar.

    Phew. That was fun. Now, let's learn how to use our scrollbar in a real movie with other content, layers,and data.

    By now, you should have a working scrollbar in place. If you do not, visit the previous pages (1, 2, 3) tosee which step you may have skipped. Now that you have created the scrollbar, you will learn how toactually use it and modify it for your own needs.

    Customizing the Scrollbar

    Your scrollbar and content should look like this in your Flash right now:

  • 8/6/2019 Simple Custom Scroll in Flash

    7/18

    Because you created the above for a tutorial, there wasn't much freedom in determining how everythinglooks. But, the above scrollbar is very customizable without breaking anything.

    Adjusting Height and PositionYou can adjust the height of the scrollFace, the scrollTrack, contentMain, and maskedView movie clipswhile still ensuring your scrollbar works. Remember to edit the underlying shape by right click on a movieclip and selecting Edit in Place. If you scale the movie clip object itself, you might get some unexpectedresponses to your scrolls.

    Changing Buttons/ScrollFace/ScrollTrack Styles

    Because all of your movie clips contain simple shapes, modifying them is as easy as right clicking on anyscrollbar element and selecting Edit or Edit in Place. You can replace the default shapes I told you tocreate with images, responsive buttons, and more.

    Removing the Up and Down ButtonsThe up and down buttons are not essential to the functioning of the scrollbar. You can safely removethem if you wish. From a usability point of view, it is better to have up and down buttons, though. If you

    are going for style over usability, then feel free to remove the up and down buttons.

    Note

    The only thing you do have to check is that the contentMain movie clip's y position is the same as your

    maskedView movie clip's y position.

    Place your Scrollbar inside a Movie ClipBecause this tutorial primarily focused on having you re-create the scrollbar, it did not cover topics of howto make this feature more manageable. For example, what if you wanted to add multiple scrollbars to yourmovie? You could copy and paste everything, but that would break your scrollbar because there would beduplicate instance names for all of your GUI elements.

    A great solution would be to place all of your scrollbar elements into a movie clip as opposed to creatingeverything out in the open on the main timeline. By placing your scrollbar inside a separate movie clip,you can place several versions of your scrollbar in the same Flash document, and you can move yourentire scrollbar(s) around easily. Instead of having to unlock all layers, selecting all of the objects, andthen moving everything to a new spot, you instead just move your movie clip containing your entirescrollbar instead.

    The following is a screenshot of me dragging a movie clip containing my scrollbar:

  • 8/6/2019 Simple Custom Scroll in Flash

    8/18

    [ dragging the movie clip containing a scrollbar ]

    Place Everything on IntegersPlace all of your scrollbar elements on integer x and y positions. In other words, there should be nodecimal values for either the height, width, or x and y positions when you look in the Properties panelafter selecting any object.

    That is all there is to learning how to use the scrollbar. There really isn't much to it, and in the next fewpages, you will learn how I approached the design of the scrollbar and why the code you copied and

    pasted works the way it does.ApproachYou know that the scrolling area is going to be considerably smaller than the actual content contained init. Our goal is to display only a small portion of our content in our viewing area. We need to providefunctionality for allowing the viewer to adjust which portion of the larger content to display in the smallerviewing area.

    The following diagram should help you to visualize what I will be explaining:

  • 8/6/2019 Simple Custom Scroll in Flash

    9/18

    The height of our content is denoted by H_C, and the height of our scrollTrack is H_T. H_F refers to theheight of our scrollface. Therefore, you now have an idea of our constraints. Our scrolling is constrainedby the height of our content, the height of the viewing area, the height of the scroll track, and the theheight of our scroll face.

    Initially, a height H_V of your content is already being displayed in your viewing area. So the total heightthat we need to scroll is going to be H_C minus H_V. You now know the total height you have to scroll.Glancing at the above diagram, you can see that you have a distance of H_T to scroll through a height(H_C - H_T) of content.

    Our relationship for scrolling so far is:

    (H_C - H_V) / H_T

    Let's use some real numbers. If your content is 1000 pixels tall (H_C), and both your maskedView andscrollTrack is 200 pixels tall (H_V, H_T). That means, since 200 pixels are already being displayed, youwill need to scroll through 800 pixels of content. You only have 200 pixels of scrollTrack to do that in. Thatmeans, 800 pixels of content divided by 200 pixels of scrollTrack yield 4 pixels of content scrolled per 1pixel of scrolling done by your scrollTrack.

    That makes sense! Because for every pixel you scroll, you have to scroll more pixels of your content inorder to get through all the content before you reach the end of your scrollTrack. We are not done quiteyet.

    There is a slight complication. Your scrollFace has a height also, and it takes up valuable space also! Thefull height of our scrollTrack cannot be used, because the bottom edge of the scrollFace stops once itreaches the bottom of your scrollTrack. That means you have to take into account the space used up byscrollFace.

    Devising a relation between the scroll track's height and the scroll face's height is straightforward. Thedistance you move the scrollFace cannot be H_T. My next guess would be H_T - H_F. And that is ouranswer. Now, your modified relation between the content height, the scrollFace height, and thescrollTrack height is:

  • 8/6/2019 Simple Custom Scroll in Flash

    10/18

    (H_C - H_V) / (H_T - H_F)

    Let's revisit our example from above. If you substitute in the values for H_C, H_T, and H_F, you get 800 /180 which is around 4.44. It's an ugly number, but good thing our computers can do this stuff better thanus. Every pixel you drag your scrollFace, your content is dragged about 4.44 pixels.

    All we have to do now is take into account our scrollFace's initial height so that we can offset our result bythe space taken up by the scrollFace, and we have our final formula for implementing our scroll bar:

    ((H_C - H_V) / (H_T - H_F))

    This is really the hard part of this tutorial. On the next page, I'll explain the code that takes all of the aboveand more and translates it into a format that Flash understands.

    ActionScript Explained

    varscrollHeight:Number=scrollTrack._height;

    varcontentHeight:Number=contentMain._height;

    varscrollFaceHeight:Number=scrollFace._height;

    varmaskHeight:Number=maskedView._height;

    I declare variables to store the heights of our four major scrollbar elements: the scroll track, the content,the scroll face, and the viewing/masked area.

    varinitPosition:Number=scrollFace._y=scrollTrack._y;

    varinitContentPos:Number=contentMain._y;

    varfinalContentPos:Number=maskHeight-contentHeight+initContentPos;

    These three lines store the initial and final position our content should be. Because the initial and finalpositions are related to the positions of our scrollFace, scrollTrack, maskHeight, and contentMain, I justcreate more variables to store variations of similar data you collected in the above section.

    varleft:Number=scrollTrack._x;

    vartop:Number=scrollTrack._y;

    varright:Number=scrollTrack._x;

    varbottom:Number=scrollTrack._height-scrollFaceHeight+scrollTrack._y;

    Similar to what I have been doing, I'm declaring more variables and assigning them numerical propertiesfrom our scrollbar elements. With these four lines of code, I specify co-ordinates for a virtual box in whichour scroll face's movements are restricted. You will see these being used when the startDrag function iscalled later.

    Notice that the bottom variable assignment seems more complicated and longer than the other variableassignments. What I am doing is trying to find the bottom limit we can scroll our scroll face on thescrollTrack.

  • 8/6/2019 Simple Custom Scroll in Flash

    11/18

    The following diagram should help:

    Because our scrollHeight variable stores the height of our track, we need to subtract the height taken upby our scrollFace - denoted as scrollFaceHeight. The scrollTrack._y value is important because bothyour scrollHeight and scrollFaceHeight values do not change relative to where you place them on themovie. They are absolute values because the height of your scrollFace and scrollTrack will not changebased on the position you place them.

    The problem, though, is that the bottom variable defines a specificY position that will act as scrollFace'sbottom boundary. By adding scrollTrack._y into the mix for bottom offsets the value for bottom by takinginto account the distance the top edge of your scrollTrack is from Flash's origin. This ensures thatyourbottom variable contains data that is relative to where your scrollTrack is in relation to your movie's

    origin.

    vardy:Number=0;

    varspeed:Number=10;

    varmoveVal:Number=(contentHeight-maskHeight)/(scrollHeight-scrollFaceHeight);

    With these lines, I move away from defining and re-defining scrollbar element properties and movetowards defining variables that make managing our code easier.

    The variable dy stores the change in the y position resulting from dragging the scroll face. You will see itdoing more than just storing the value 0 later.

    The speed variable controls how quickly the content scrolls each time you press the Up or Down buttons.

    Finally, the moveVal variable stores the ratio of how much your content moves based on how much thescrollFace moved on the scrollTrack. In other words, the relationship between all four of our scrollbardesign elements (outlined in the previous page) are stored in this variable.

    Tip

    Initializing this many variables may seem like a waste of time. After all, typing contentMain._y takes upalmost as much time as declaring and using a variable called contentHeight.

    What declaring variables does, though, is make the code more readable and ensure you have an idea ofwhat you think are the important parts of the code that will be used frequently.

    More importantly, declaring variables using descriptive English names allows you think about the biggerconcepts you are tackling as opposed to worrying about the non-essential code syntax and relateddetails.

  • 8/6/2019 Simple Custom Scroll in Flash

    12/18

  • 8/6/2019 Simple Custom Scroll in Flash

    13/18

    This is a nested event handler because it is contained within the onPress event covered above. Theabove code executes when your scrollFace (this) is dragged. In order to drag, you first click on thescrollFace, and then you move your mouse in the direction you want to drag.

    When you click on the scrollFace, any code contained inside the onPress event executes. And when youmove your mouse while you still have your mouse button pressed, the code in

    the this.onMouseMove function executes.

    dy=Math.abs(initPosition-this._y);

    contentMain._y=Math.round(dy*-1*moveVal+initContentPos);

    The dy variable returns the difference in position between your scroller's initial position and where it isnow.

    con

    tentM

    ain._y=M

    ath.

    round(dy*-1*m

    oveVal

    +initC

    onte

    ntP

    os);

    This line sets the y position of your contentMain movie clip. Notice the three variables that are used tospecify the position: dy, moveVal, and initContentPos.

    If you recall, moveVal specifies how many pixels of the contentMain movie clip you move for each pixelyour scrollFace moves. With dy specifying how many pixels your scrollFace has moved so far, multiplyingdy by moveVal results in the total distance our contentMain movie clip should move based on where yourscrollFace is currently.

    Because Flash's co-ordinate system is upside down, I multiply the value by -1 to get things right side upagain. Sometimes, your scroller may have everything starting from the origin, but sometimes, it may not.Therefore, all of your data is offset by initContentPos, which is simply the same as getting the y position

    of your scroll track.

    I place all of the above in a Math.round() function, because that will ensure that your contentMain clip's yposition is always an integer value. Text and some graphics become blurry when they are positioned onnon-integer values. In order to avoid such blurriness in the content, Math.round() ensures yourcontentMain movie clip's position stays in integer increments.

    scrollFace.onMouseUp=function(){

    stopDrag();

    deletethis.onMouseMove;

    };

    This section of code is, thankfully, pretty straightforward. The above code executes when you are nolonger pressing your mouse and/or dragging the scrollFace.

  • 8/6/2019 Simple Custom Scroll in Flash

    14/18

    The stopDrag() function reverses the startDrag function from earlier and stops the dragging. Deleting thethis.onMouseMove function stops your scrollFace from following your mouse even after you have stoppeddragging.

    Up and Down ButtonsWe now shift gears and away from talking about the scrollFace to talking about the buttons. Because theUp and Down buttons are similar, I will only cover the Up button in detail.btnUp.onPress=function(){

    this.onEnterFrame = function() {

    if (contentMain._y+speed

  • 8/6/2019 Simple Custom Scroll in Flash

    15/18

    if(contentMain._y+speed

  • 8/6/2019 Simple Custom Scroll in Flash

    16/18

    contentMain._y=maskedView._y;

    deletethis.onEnterFrame;

    In the above section, you learned what would happen if our content had not reached its final position. Thiscode is executed when our content is about to reach its boundary.

    Because we can no longer move up, the positions are reset to the default 'up' values. scrollFace isrestored to its top position, contentMain is restored to itsmaskedView._y position, and finally, we deleteour onEnterFrame because there is no need for it any more. We have exhausted all we can do to our upbutton.

    btnUp.onDragOut=function(){

    deletethis.onEnterFrame;

    };

    btnUp.onMouseOut=function(){

    deletethis.onEnterFrame;

    };

    When you are no longer pressing the up button or you click and drag away from the up button, I stop anywork done by the up button by deleting the onEnterFrame contained in it.

    if(contentHeight

  • 8/6/2019 Simple Custom Scroll in Flash

    17/18

    In the next page, I will briefly explain how the down button works and wrap up what ended up becoming a9 page tutorial.The Down ButtonThe code for the down button is very similar to the code used for creating the up button:

    btnDown.onPress=function(){

    this.onEnterFrame=function(){

    if(contentMain._y-speed>finalContentPos){

    if(scrollFace._y>=bottom){

    scrollFace._y=bottom;

    }else{

    scrollFace._y+=speed/moveVal;

    }

    contentMain._y-=speed;

    }else{

    scrollFace._y=bottom;

    contentMain._y=finalContentPos;

    deletethis.onEnterFrame;

    }

    };

    };

    btnDown.onRelease=function(){

    deletethis.onEnterFrame;

    };

    btnDown.onDragOut=function(){

    deletethis.onEnterFrame;

    };

    The only difference is that while the up button focused on the top boundaries for both the content andscroll face, the down button focuses on the bottom boundaries.

    Besides minor changes associated with ensuring both the scroller and content work properly as theyapproach the bottom boundary, the code itself is nearly the same.

  • 8/6/2019 Simple Custom Scroll in Flash

    18/18

    ConclusionYou are now done with this tutorial. The most complicated thing about this tutorial, from my point of view,is getting the scroll face and the content synchronized. Because you are rounding the y position for thecontent movie clip, our mathematical relation linking all of our scrollbar elements will not work withoutadjusting for them. You saw such subtle adjustments in my up and down button implementations.When you are scrolling through several hundred pixels, minor rounding errors can eventually result in amajor discrepancy between your intended result and the final result. That is why you see a lot* of code forthe btnUp and btnDown buttons to ensure that, to the eye, it looks as if both the scroll face and up/downbuttons seem to work seamlessly together.

    * Ok, it's not a lot, but it's certainly more than what it is necessary for such a simple task.

    Note - Improved Versions

    Optimized CodeMichaelxxOA did a great job optimizing and improving the code featured in this scrollbar tutorial. You canfind his source file and code by clicking here.

    Mousewheel Support28bit created a version of the code that allows mouse scrolling.