开发者

Scrollview Optimizations

I have a scrollview that contains a custom view. The custom view is bigger than th开发者_C百科e area of the screen and draws properly.

The scrollview however tends to call onDraw() non-stop when scrolling, and I can't seem to make it smooth.

I used ScrollView.getDrawingRect() to calculate the visible portion of the screen and only draw to that, but it still returns the entire viewport (so it's optimized to not draw offscreen areas), and not the delta between the last position and the current one. Ideally I'd want to draw only the delta, and not the entire visible window.

If anyone can point me to more information about how to use the drawing caches, and if that will help optimize scrolling, I'd love to implement it, or any other possible solutions it would be greatly appreciated.


When content is scrolled, the entire viewport needs to be redrawn because all of the content has moved. I don't think there's anything that needs to be done to optimize a ScrollView - if scrolling is slow then it's the drawing method of your custom view that is too slow.

Try to avoid object creation in your draw methods which is usually the main culprit for poor drawing performance.

Edit: Also the scrollview could blit the old content up or down quickly that is still drawn on the screen, and then request a redraw of only the "new" portion of the screen. (only applies to opaque views).


I encountered the same problem. I solved it by using the function setDrawingCacheEnabled(true). By enabling this setting, your canvas view will be cached as bitmap, so you don't have to call canvas' draw method each time onDraw() is called.

In your custom view's constructor, you will need something like this:

public CustomView(Context context) {
    setDrawingCacheEnabled(true);
    drawnFlag = false;
}

In your onDraw method, you will need something like this:

public void onDraw(Canvas canvas) {
    if (! drawnFlag) {
        canvas.drawPath(...);
        canvas.drawPath(...);
        drawnFlag = true;
    }
}

Now, scrolling on this custom view should be smooth since we only call the drawing methods once.


Afaik the ScrollView sets a proper clip rect on the canvas your view gets in onDraw so you only need to draw what's inside that rect. You could also implement cache bitmaps based on the clip rect's size.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜