2012-07-10 60 views
3

在我的iPad應用程序,我有一個UITableView是分配/ inits每次UIView子類新的細胞被選中。我重寫drawRect:在此UIView的繪製徑向漸變,它工作正常,但性能是痛苦 - 當細胞被竊聽,UIView的需要相當長以編程方式繪製一個漸變,而不是使用巴紐爲背景。有沒有什麼辦法「緩存」我drawRect:方法或它生成的提高性能的梯度?我寧願使用drawRect:而不是.png。我的方法是這樣的:優化CGContextDrawRadialGradient中的drawRect:

- (void)drawRect:(CGRect)rect 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    size_t gradLocationsNum = 2; 
    CGFloat gradLocations[2] = {0.0f, 1.0f}; 
    CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.5f}; 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum); 
    CGColorSpaceRelease(colorSpace); 

    CGPoint gradCenter = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); 
    float gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ; 

    CGContextDrawRadialGradient (context, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation); 

    CGGradientRelease(gradient); 
} 

謝謝!

回答

2

可以渲染的圖形爲背景,然後保存,作爲一個UIImage。 This answer應該讓你開始:

drawRect:是用來繪製的觀點本身,而不是預先創建圖形對象上UIView的方法。

因爲它似乎要創造形狀來存儲它們,後來畫,似乎合理的生成形狀爲UIImage和使用UIImageView吸引他們。 UIImage可以直接存儲在NSArray中。

爲了創建圖像,執行以下操作(在主隊列中;在不:)的drawRect:

1)創建位圖上下文

UIGraphicsBeginImageContextWithOptions(size, opaque, scale); 

2)得到的上下文

CGContextRef context = UIGraphicsGetCurrentContext(); 

3)繪製任何你需要

4)出口的背景下成圖像

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 

5)破壞的背景下

UIGraphicsEndImageContext(); 

6)參考存儲圖像

[yourArray addObject:image]; 

重複你要創建的每個形狀。

細節見documentation用於上述功能。爲了更好地理解在drawRect:中繪製和在程序中的任意位置之間的區別以及通常使用上下文的區別,我建議您閱讀Quartz2D Programming Guide,尤其是圖形上下文部分。

+0

有對Objective-C的沒有高亮提示,據我可以告訴。普通C會工作嗎? – 2012-11-18 06:06:03

+0

我已經看到了我的方式的錯誤,並會悔改:)(感謝您的編輯) – 2015-11-28 04:49:15