滚动视图优化
我有一个包含自定义视图的滚动视图。自定义视图比屏幕区域大并且可以正确绘制。
然而,滚动视图在滚动时往往会不停地调用 onDraw() ,而我似乎无法使其平滑。
我使用 ScrollView.getDrawingRect() 来计算屏幕的可见部分,并且只绘制到该部分,但它仍然返回整个视口(因此它经过优化以不绘制屏幕外区域),而不是最后一个位置和当前位置之间的增量一。理想情况下,我只想绘制增量,而不是整个可见窗口。
如果有人可以向我指出有关如何使用绘图缓存的更多信息,并且这将有助于优化滚动,我很乐意实现它,或者任何其他可能的解决方案,我将不胜感激。
I have a scrollview that contains a custom view. The custom view is bigger than the 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当内容滚动时,需要重新绘制整个视口,因为所有内容都已移动。我认为不需要做任何事情来优化
ScrollView
- 如果滚动很慢,那么说明您的自定义视图的绘制方法太慢了。尽量避免在绘制方法中创建对象,这通常是导致绘制性能不佳的主要原因。
编辑:滚动视图还可以快速地将仍在屏幕上绘制的旧内容向上或向下位图传输,然后请求仅重绘屏幕的“新”部分。 (仅适用于不透明视图)。
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).
我遇到了同样的问题。我通过使用函数
setDrawingCacheEnabled(true)
解决了这个问题。通过启用此设置,您的画布视图将被缓存为位图,因此您不必每次调用onDraw()
时都调用画布的绘制方法。在自定义视图的构造函数中,您将需要类似这样的内容:
在您的
onDraw
方法中,您将需要类似这样的内容:现在,在此自定义视图上滚动应该是平滑的,因为我们只调用绘图方法一次。
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 timeonDraw()
is called.In your custom view's constructor, you will need something like this:
In your
onDraw
method, you will need something like this:Now, scrolling on this custom view should be smooth since we only call the drawing methods once.
据我所知,ScrollView 在您的视图在 onDraw 中获取的画布上设置了一个适当的剪辑矩形,因此您只需要绘制该矩形内的内容。
您还可以根据剪辑矩形的大小实现缓存位图。
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.