开发者

How to compute viewport from scrollbar?

This is probably straight forward enough but for some reason I just can't crack it (well actually its because I'm terrible at maths sadly!).

I have a viewport that shows 800 pixels at a time and I want to move it left and right over a virtual number of pixels say 2400 pixe开发者_StackOverflow社区ls wide.

I use the relative position of a scrollbar (0-1) to determine the virtual pixel that the viewport should have moved to.

I have a loop n = 800 that I run through. I want to start reading an array of plottin points from the position the slider tells me and iterate through the next 800 points from that point.

The problem I have is when my scrollbar is all the way to the right and its relative position = 1 my readpoint = 2400..... which in a way is right. But that makes my read position of plotting points go to the last point and when I begin my iteration I have no points left to read.

Based on my moving an 800 pixel wide sliding box analagy the left point of the box should be 1600 in this case and its right point should be 2400

How can I achieve this?

Do I need some sort of value mapping formula?

        private function calculateShuttleRelativePosition():void
        {

            var _x:Number=_scrollthumb.x
            _sliderCenter=_x + (_scrollthumb.width / 2)
            _sliderRange=_scrollbar.width - _scrollthumb.width;
            _slider_rel_pos=(_sliderCenter - _sliderCenterMinLeft) / _sliderRange

        }



pixel = slider relative position * 2400
readpoint= pixel


The range of your scrollbar should be the range that the left most pixel can take, not the range of all the pixels.

So your range would be 1600 (2400 - 800), not 2400 alone. This is the scaling factor you should apply to determine your offset.

As a word of warning always be on the lookout for off by one errors in these kinds of things. Since your bar ranges from 0 to 1 your outputted pixels will range from 0 to 800 if you are not careful, which could overflow your array if you don't watch out :).


The answer is actually pretty easy -- instead of making the relative position slide across the entire width (which is what you have above), you start at 0 and run to width - 800 (or the width of your viewport).

Some C-ish code for that would look like:

int viewPortWidth = 800;
int virtualWindowWidth = 2400;

// I'm assuming your code above is right -- I didn't check
float sliderRelativePosition = calculateShuttleRelativePosition(); 

// The casts (int and float here), make sure that you're rounding down to an integer 
// pixel between 0 and virtualWindowWidth - 1, inclusive
int pixel = (int)(sliderRelativePosition * (float)(virtualWindowWidth - viewPortWidth - 1));

readPixels(pixel, viewPortWidth);  // Function that loops through the pixels you want
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜