2014-01-23 40 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

相关问题