如何将UIView分成两个部分进行渲染

4

我正在尝试开发过渡效果,当一个视图分成两个部分时,上半部分向上动画,下半部分向下动画,以揭示其后面的视图。 我使用UIView和UIImageView方法来实现:

// 1. Make a screenshot:
    UIGraphicsBeginImageContext(parentView.frame.size);
    [parentView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // 2. Calculate rectangles for top and bottom part:
    CGRect rectTop, rectBottom;
    CGFloat W = rectBig.size.width;
    CGFloat H = rectBig.size.height;


    rectTop = CGRectMake(0, 0, W, y_cutoff);
    rectBottom = CGRectMake(0, y_cutoff, W, H - y_cutoff);

    // 3. Create top and bottom images:
    CGImageRef imageRefTop      = CGImageCreateWithImageInRect([screenshot CGImage], rectTop);
    CGImageRef imageRefBottom   = CGImageCreateWithImageInRect([screenshot CGImage], rectBottom);


    UIImage *imageTop = [UIImage imageWithCGImage:imageRefTop];
    UIImage *imageBottom = [UIImage imageWithCGImage:imageRefBottom];


// 4. Assign images to image views:
imageViewTop.image = imageTop;
imageViewBottom.image = imageBottom;

// 5. Animate image views:
[UIView beginAnimation:nil context:NULL];
.... animation code here
[UIView commitAnimations];

然而,这段代码在设备上非常缓慢,我相信有更有效的方法来实现这样的转换。很可能使用CALayers等方式实现。 你能指导我正确的方向吗?


1
“极慢”是什么意思?Instruments 工具在哪里显示它花费了多少时间? - rob mayoff
当点击前视图时,会触发转换。点击后会有明显的延迟,动画本身也很卡顿(在 iPhone 4 上进行了测试)。 - Lukasz
2个回答

2
动画本身不应该慢。你真正需要做的就是为动画改变两个视图的Y位置。
为什么不尝试将静态图像放入UIImageView中,然后查看动画的表现如何呢?
如果延迟发生在创建图像时,请考虑将该代码移动到单独的线程中,以便主线程不会冻结。当图像完成创建时,通知主线程,将它们放入UIImageView中,并执行动画。

2
这不是动画。您的绘图代码很慢。如果您进行分析,您将会发现renderInContext:(顺便说一下,它总是在主线程上执行)和CGImageCreateWithImageInRect是限制因素。您想要拆分的视图是什么?是否可以从一开始就创建两个视图而不是一个?

你是正确的。分析显示renderInContext方法有很多工作量。但我的视图不能被划分,因为它是一种带UIScrollView的网格菜单。它在用户点击时在动态点(触摸点)处分割。 - Lukasz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接