2012-05-14 33 views
12

我正在通過向按鈕添加線性漸變來創建花哨的UI按鈕。不過,我不知道我需要添加漸變的索引。我目前將漸變放置在圖像/文本上的代碼。iPhone iOS如何將線性漸變添加到按鈕的文本或圖像下的UIButton?

如何在文本/圖像子圖下插入子圖層到UIButton?對我來說保持一個按鈕的文字和圖像可見!

+(void)addLinearGradientToView:(UIView*)view TopColor:(UIColor*)topColor BottomColor:(UIColor*)bottomColor 
{ 
    for(CALayer* layer in view.layer.sublayers) 
    { 
     if ([layer isKindOfClass:[CAGradientLayer class]]) 
     { 
      [layer removeFromSuperlayer]; 
     } 
    } 
    CAGradientLayer* gradientLayer = [CAGradientLayer layer]; 

    gradientLayer.startPoint = CGPointMake(0.5, 0); 
    gradientLayer.endPoint = CGPointMake(0.5,1); 
    gradientLayer.frame = view.bounds; 
    gradientLayer.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil]; 
    // [view.layer addSublayer:gradientLayer]; 
    if(view.layer.sublayers.count>0) 
    { 
     [view.layer insertSublayer:gradientLayer atIndex:view.layer.sublayers.count-2]; 
    }else { 
     [view.layer addSublayer:gradientLayer]; 
    } 
} 
+0

我寫了一些示例代碼來做這種事情:https://github.com/kristopherjohnson/gradientbuttons –

回答

44

將它添加到您的自定義按鈕的層:

CAGradientLayer *gradientLayer = [CAGradientLayer layer]; 
gradientLayer.frame = customButton.layer.bounds; 

gradientLayer.colors = [NSArray arrayWithObjects: 
         (id)[UIColor colorWithWhite:1.0f alpha:0.1f].CGColor, 
         (id)[UIColor colorWithWhite:0.4f alpha:0.5f].CGColor, 
         nil]; 

gradientLayer.locations = [NSArray arrayWithObjects: 
          [NSNumber numberWithFloat:0.0f], 
          [NSNumber numberWithFloat:1.0f], 
          nil]; 

gradientLayer.cornerRadius = customButton.layer.cornerRadius; 
[customButton.layer addSublayer:gradientLayer]; 

其中customButton是您的自定義UIButton

+1

此解決方案不能100%正常工作。按鈕確實得到了一個漸變,但它在底角溢出。請參閱:https://www.dropbox.com/s/mguy6owuayjgxvc/Screen%20Shot%202012-09-03%20at%2017.50.30.png這怎麼解決? – murze

+2

@murze看起來像您的按鈕或其容器視圖缺少要設置的clipsToBounds = YES屬性。這會削減您遇到的溢出。 – Luke

+1

[gradientLayer.masksToBounds = YES]; < - do that – stackOverFlew

9

對於你正在努力實現的,總是在索引0

插入我寫an article對這樣的事情最近,你可能會覺得有趣。

+0

謝謝!添加漸變圖層後,我的文字缺失,但僅在iOS 6中,iOS 7仍顯示文字。更改爲插入後,現在適用於兩者。 – KevinS

0

下面是代碼來實現這一

CAGradientLayer *gradient = [CAGradientLayer layer]; 
gradient.frame = <#View Variable Name#>.bounds; 
gradient.colors = [NSArray arrayWithObjects:(id)([UIColor colorWithRed:0.337 green:0.596 blue:1.000 alpha:1.000].CGColor),(id)([UIColor colorWithRed:0.757 green:0.459 blue:1.000 alpha:1.000].CGColor),(id)([UIColor colorWithRed:0.310 green:0.835 blue:1.000 alpha:1.000].CGColor),nil]; 
gradient.startPoint = CGPointMake(0.5,0.0); 
gradient.endPoint = CGPointMake(0.5,1.0); 
[<#View Variable name#>.layer insertSublayer:gradient atIndex:0]; 

我得到了這個工具,可以很容易地選擇你的顏色,並自動輸出漸變的代碼。非常好用我每天都用它 itunes.apple.com/gb/app/gradient-creator/id1031070259?mt=12

相關問題