2013-04-12 26 views
3

我知道向UIView添加背景漸變的幾種方法。我想知道什麼是最有效和可擴展的方式,爲什麼?下面是我使用的技術:向UIView添加漸變的現代技術

  • 創建的UIView子視圖並覆蓋drawRect中,在那裏我畫在目前情況下的梯度。

    a。當使用上面的漸變創建它與視圖的邊界我想裝飾和插入此背景漸變作爲第一個子視圖,即– insertSubview:atIndex:

    b。後我從上面的背景漸變視圖,我呈現在圖像上下文,並使用它作爲背景圖像,即

     
    UIGraphicsBeginImageContext(gradView.bounds.size); 
    [gradView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *gradientImg = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    UIColor *background = [UIColor colorWithPatternImage:gradientImg]; 
    self.view.backgroundColor = background; 
    
  • 創建伸縮性PNG並用它來裝飾視圖背景。技巧與你裝飾UIButton的方式非常相似。

     
    -(UIColor *)backgroundColor:(CGRect)frame 
    { 
        UIImage *bg = [UIImage imageNamed:@"background_23x36"]; 
        bg = [bg resizableImageWithCapInsets:UIEdgeInsetsMake(0.0, 11.0, 0.0, 11.0)]; 
        UIGraphicsBeginImageContextWithOptions(frame.size, YES, [[UIScreen mainScreen] scale]); 
        [bg drawInRect:frame]; 
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
        UIGraphicsEndImageContext(); 
        return [UIColor colorWithPatternImage:image]; 
    } 
    
  • 創建的UIView子視圖但不是覆蓋drawRect中,使用CAGradientLayer。類似http://nscookbook.com/2013/04/recipe-20-using-cagradient-layer-in-a-custom-view/

那麼什麼是最有效和可擴展的方式來添加漸變作爲背景?

+1

我會在視圖的drawRect中做到這一點。使用CGGradient – Fogmeister

回答

9

如上面Fogmeister建議的那樣,在UIView子類的drawRect:方法中執行。

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

    NSArray *gradientColors = [NSArray arrayWithObjects:(id) [UIColor redColor].CGColor, [UIColor yellowColor].CGColor, nil]; 

    CGFloat gradientLocations[] = {0, 0.50, 1}; 
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) gradientColors, gradientLocations); 

    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect)); 
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect)); 

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0); 
    CGGradientRelease(gradient); 
    CGColorSpaceRelease(colorSpace); 
} 
+0

我在上面的一種方法中做到了這一點,但是在獲得漸變視圖之後,將其作爲子視圖添加到索引0還是從漸變視圖圖像生成顏色並將其用作背景顏色更有效? – atkabai

+0

您可以製作任何需要從UIView類繼承的漸變背景的視圖,該類通過其重寫的drawRect方法繪製漸變。如果需要,可以對漸變顏色和位置進行參數化。 – jverrijt

+1

在完成色彩空間後,不要忘記調用'CGColorSpaceRelease(colorSpace)'。 –

0

DrawRect是我認爲更有效的方法。我想擴展jverrijt的很好的答案。如果你需要alpha分量(對黑色漸變f.e.透明),那麼你可以使用這個:

UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0); 
CGContextSaveGState(UIGraphicsGetCurrentContext()); 
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear); 
CGContextRestoreGState(UIGraphicsGetCurrentContext()); 

//Draw stuffs 

UIGraphicsEndImageContext();