ios - 不同 View 的 CAGradientLayer

标签 ios uiview cagradientlayer

我想用 CAGradientLayer 为不同尺寸的多个 View 创建一个颜色渐变。不知道怎么单独定义frame:

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];   ???

谢谢!

最佳答案

-(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];
}

然后将此代码用于您的三个 View :

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

关于ios - 不同 View 的 CAGradientLayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21319799/

相关文章:

ios - UIVIew 大小在界面生成器中使用设备大小并且没有限制

iOS白色到透明渐变层为灰色

ios - SwiftUI - 动画计数文本从 0 到 x

ios - 如何在 iPhone 应用程序中实现本地缓存 Web 服务数据检索?

android - 图像资源从 native 应用程序中消失

ios - 如何阻止从 super View 到 subview 的手势?

ios - 将 UIView 添加到 tableFooterView 时 UITableView 抛出异常

ios - 我想创建一个Cagradientlayer子类/实用程序类

swift - CAGradientLayer 不绘制形式掩码

ios - SDK iOS 8.0 中的产品类型单元测试包需要代码签名