2011-12-08 52 views
4

我試圖開發過渡效果,當一個視圖分成兩部分,上部分向上動畫,下部分向下動畫以欣賞背後的視圖。 我使用的UIView和UIImageView的方式來實現這一目標:如何將UIView渲染爲兩部分

// 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

「極其緩慢」是什麼意思?儀器在哪裏說它正在花費時間? –

+0

單擊前視圖時會觸發轉場。點擊後有明顯的延遲,動畫本身是生澀的(在iPhone 4上測試)。 – Lukasz

回答

2

這不是動畫。你的繪圖代碼很慢。如果你的配置文件,你會看到renderInContext:(btw。總是在主線程上執行)和CGImageCreateWithImageInRect是限制因素。你的觀點(你想分裂的觀點)是關於什麼?是否可以從頭開始創建兩個視圖而不是一個視圖?

+0

你說得對。分析在renderInContext方法中顯示了很多努力。但是我的觀點不能被分割,因爲它是UIScrollView的一個網格菜單的王者。它在用戶點擊它時在動態點(觸摸點)處分開。 – Lukasz

2

動畫本身不應該慢。你真正需要做的是改變動畫兩個視圖的Y位置。

爲什麼不嘗試將靜態圖像放入UIImageViews並查看動畫如何執行呢?

如果在創建圖像時發生延遲,也許應該考慮將該代碼移動到單獨的線程,以便主線程不會凍結。當圖像完成創建後,通知主線程,將它們放入UIImageViews中,並執行動畫。