【问题标题】:CAGradientLayer for different views用于不同视图的 CAGradientLayer
【发布时间】:2014-01-23 21:33:45
【问题描述】:

我想用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];   ???

谢谢!

【问题讨论】:

  • 为什么不为每个新的视图/尺寸创建一个新的渐变层呢?我不确定是否要重新使用 CAGradientLayer。
  • 谢谢Putz,这肯定行得通,但我希望找到一种解决方案,可以避免多次重复相同的代码。
  • 我将发布一些代码作为答案,以表明它并不是真正重复的代码。随心所欲地使用它。

标签: ios uiview cagradientlayer


【解决方案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];

【讨论】:

  • 但是 view.bounds 中的视图现在是一个未声明的标识符。
  • 我喜欢这样。非常感谢你。渐变视图尺寸不会针对更大的屏幕尺寸进行更新。任何的想法?还是谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 2013-06-19
  • 2020-12-21
  • 2019-08-29
  • 2019-03-01
  • 1970-01-01
相关资源
最近更新 更多