我有一个有点滞后的动画,我已将其缩小为:
作为动画的一部分,UIScrollView
会自动滚动。即使 subview 看起来已加载,如果它们在 ScrollView 边界之外,那么 drawRect:
将在这些 View 上被调用,因为它们被动画回到可见区域(我正在实现我自己的drawRect:
在每个 View 上)。这就是让我的动画卡顿的原因。
我已经为每个 ScrollView 的 subview 将 shouldRasterize 设置为 true,没有区别。我如何强制 UIScrollView
将每个 View 保存在内存中,即使超出 ScrollView 的边界也是如此?
最佳答案
将您的绘图代码从 draw rect 移到其他方法中。 而不是渲染到 View 的上下文中渲染到图像上下文中。将此方法添加到绘图代码的开头以创建图像上下文:
UIGraphicsBeginImageContextWithOptions(
CGSize size,
BOOL opaque,
CGFloat scale
);
像这样使用它:
UIGraphicsBeginImageContextWithOptions(
self.bounds.size,
NO, //if you are doing rounded corners or anything, else YES
0.0 //Scales automatically for retina displays
);
//Need a reference to the context you just made?
CGContextRef ctx = UIGraphicsGetCurrentContext();
您的 CG 绘图代码正常工作。然后将上下文渲染为图像
UIImage * renderedImage = UIGraphicsGetImageFromCurrentImageContext();
不要忘记
UIGraphicsEndImageContext();
从只在需要时绘制的地方调用此绘制代码。这些是您可以覆盖的一些候选方法:
- (void)willMoveToSuperview:(UIView *)newSuperview //called when adding to a view
- (void)layoutSubviews //called when first displayed, on frame change and after setNeedsLayout has been called.
然后在 View 上设置这些图像。如果你有按钮,你应该有 UIButton 的子类。你现在可以 - (void)setImage:(UIImage *)image forState:(UIControlState)state
Et voila, performace!
关于iphone - 如何停止 UIScrollView 调用 drawRect : on sublayers that go in/out of the visible region?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14235804/