2014-01-23 43 views
0

我想用CAGradientLayer爲不同大小的多個視圖創建顏色漸變。我不知道如何分開定義框架:適用於不同視圖的CAGradientLayer

UIColor *darkOp = [UIColor colorWithRed:0.2f green:0.2f blue:0.27f alpha:1.0]; 
UIColor *lightOp = [UIColor colorWithRed:0.36f green:0.35f blue:0.42f alpha:1.0]; 

// Create the gradient 
CAGradientLayer *gradient = [CAGradientLayer layer]; 

// Set colors 
gradient.colors = [NSArray arrayWithObjects: 
        (id)darkOp.CGColor, 
        (id)lightOp.CGColor, 
        nil]; 
//set radius 
gradient.cornerRadius = 5.0; 

// Set bounds BUT just for one view size 
gradient.frame = self.numberRegionView.bounds; //<-- here I can just define one frame size 

// Add the gradient to one view 
[self.numberRegionView.layer insertSublayer:gradient atIndex:0]; 

//but how to add the gradient layer to views with different sizes ??? 
//[self.graphRegionView.layer insertSublayer:gradient atIndex:0]; ??? 
//[self.barRegionView.layer insertSublayer:gradient atIndex:0]; ??? 

謝謝!

+0

爲什麼不爲每個新視圖/尺寸新的漸變層?我不確定是否需要重新使用CAGradientLayer。 – Putz1103

+0

感謝Putz,這肯定會工作,但我希望找到一個解決方案,可以避免多次重複相同的代碼。 – JFS

+0

我會張貼一些代碼作爲答案,以顯示它並非真正重複的代碼。如你所願使用它。 – Putz1103

回答

1
-(void)setGradientForView:(UIView*)view 
{ 
    static UIColor *darkOp = [UIColor colorWithRed:0.2f green:0.2f blue:0.27f alpha:1.0]; 
    static UIColor *lightOp = [UIColor colorWithRed:0.36f green:0.35f blue:0.42f alpha:1.0]; 

    // Create the gradient 
    CAGradientLayer *gradient = [CAGradientLayer layer]; 

    // Set colors 
    gradient.colors = [NSArray arrayWithObjects: 
        (id)darkOp.CGColor, 
        (id)lightOp.CGColor, 
        nil]; 
    //set radius 
    gradient.cornerRadius = 5.0; 

    // Set bounds BUT just for one view size 
    gradient.frame = view.bounds; //<-- here I can just define one frame size 

    // Add the gradient to one view 
    [view.layer insertSublayer:gradient atIndex:0]; 
} 

然後使用此代碼爲你的三個觀點:

[self setGradientForView:self.numberRegionView]; 
[self setGradientForView:self.barRegionView]; 
[self setGradientForView:self.numberRegionView]; 
+0

但是,view.bounds現在是一個未聲明的標識符。 – JFS

+0

哦,堅持我沒有看到頂部... – JFS

+0

我喜歡那樣。非常感謝你。較大的屏幕尺寸不會更新漸變視圖尺寸。任何想法?不管怎麼說,還是要謝謝你! – JFS

相關問題