iphone - 如何停止 UIScrollView 调用 drawRect : on sublayers that go in/out of the visible region?

标签 iphone ios objective-c ipad animation

我有一个有点滞后的动画,我已将其缩小为:

作为动画的一部分,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/

相关文章:

iphone - 在 uiview 上具有不同位置的对象

iphone - 核心动画从屏幕外到屏幕上的动画

html - 将 HTML 拆分为页面,不将行切成两半

iphone - Objective-C 中的文本作为超链接

objective-c - Objective-C 中 main() 的等价物是什么?

iphone - 如何在 iPhone 中比较两个日期?

html - 尽管将其设置为 scale=1,但 Bootstrap 模型未在 iPhone 5s 的全视口(viewport)中显示

ios - Swift 链接器错误 : Undefined symbol for surely available API presentationDimensions

ios - 在 StoryBoard 中调整 Collection View 标题的大小

objective-c - 延迟动画开始后,UIButton 上的触摸事件停止