改善image的繪製性能 -(void)drawRect:

通常狀況下,無論目標是什麼ios設備,你都應該避免頻繁的調用-drawRect:。爲了改善你的應用在iphone4上的性能這是特別關鍵的,由於相對於其餘iphone你有4倍的像素量須要填充。
若是你偶然趕上了圖片繪製性能的問題,那麼可能你在你的視圖的-drawRect:方法中使用CGContextDrawImage或 UIImage/-drawInRect:方法繪製圖像,無效或快速重繪這個視圖...
注意,由於 iPhone/iPod touch/iPad更新屏幕,若是你調用setNeedsDisplayInRect: 或 -setNeedsDisplay:,整個視圖都會被重繪。html

重要:每一個UIView都是做爲一個單個的元素。當你setNeedsDisplayInRect: or -setNeedsDisplay:請求部分或者所有重繪,整個的視圖將被標記爲更新。ios

每一個UIView都支持CALayer和images做爲layer的內容保存在內存中,只有CALayer還在視圖層級中。意思是你在應用程序中看到的大部分操做,包括視圖或layer的移動、旋轉、縮放,不須要重繪。最好的圖片動畫方式是建立圖片的視圖或layer,而後使用Core Annimation去實現任何動畫。這種方法能避免調用-drawRect: ,並所以調用CGContextDrawImage or UIImage/-drawInRect:。緩存

用一個簡單的例子說明下,假設你想在繪製一個精靈圍繞z軸旋轉垂直於屏幕。一種方法是每一個動畫步驟在視圖的-drawRect:方法中當前的矩陣變換(CGContextRotateCTM)應用旋轉矩陣而且重繪圖片(CGContextDrawImage)。然而,一個更高效的方法是設置的CALayer的contents屬性爲這個圖片,而後使用動畫層的transform屬性去完成旋轉動畫。app

若是你在一個圖像上有獨立的移動的組件,那麼你應該分解到獨立的視圖或layers,單獨的執行動畫。例如,若是你繪製一個可拖動的圖像,當處理移動的 時候,你應該放在獨立的層,而後移動這個層,而不是invalidate整個圖像視圖。iphone

有些狀況(不是大多數)CALayer和Core Animation不起做用。對這些狀況,記住CGContextDrawImage和UIImage/-drawInRect: 必須花費大量的時間去解壓或從新採樣這個圖片,由於圖片不會被緩存到layer tree中。ide

警告:調用像 CGContextDrawImage 和 UIImage/-drawInRect: 繪製圖像是要付出特別昂貴的代價,當他們必須解壓或縮放圖片顯示的時候。性能

1.在UIImageView中設置一個UIImage做爲layer的內容動畫

// 這也會設置view的contentScaleFactor給圖片的scale factor
imageView.image = image;

2. 視圖z周的旋轉動畫spa

- (void)rotateView:(UIView *)view toAngle:(float)angle {     
    [UIView beginAnimations:nil context:nil];     
    [view setTransform:CGAffineTransformMakeRotation(angle)];     
    [UIView commitAnimations]; 
}

3. 調整UIImage尺寸,結果能夠緩存在image array中翻譯

- (UIImage*)resizeImage:(UIImage*)image toWidth:(NSInteger)width height:(NSInteger)height
{
    // Create a graphics context with the target size
    // On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
    // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
    CGSize size = CGSizeMake(width, height);
    if (NULL != UIGraphicsBeginImageContextWithOptions)
        UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    else
        UIGraphicsBeginImageContext(size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    // Flip the context because UIKit coordinate system is upside down to Quartz coordinate system
    CGContextTranslateCTM(context, 0.0, height);
    CGContextScaleCTM(context, 1.0, -1.0);

    // Draw the original image to the context
    CGContextSetBlendMode(context, kCGBlendModeCopy);
    CGContextDrawImage(context, CGRectMake(0.0, 0.0, width, height), image.CGImage);

    // Retrieve the UIImage from the current context
    UIImage *imageOut = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return imageOut;
}


翻譯自官網

相關文章
相關標籤/搜索