ios - 如何为 UIButton 设置自定义渐变背景?

标签 ios uibutton gradient cagradientlayer

我想创建一个自定义的 UIButton 渐变背景。我附上了一些关于要求的图片。
enter image description here
enter image description here

但是我的渐变背景并不像我预期的那样。

enter image description here

我的问题是如何设置position或location为渐变? (从上到中,然后从中到下)。

这是我的代码:

- (void)setBlueShiningLayer {
    CALayer *buttonLayer = self.layer;
    [buttonLayer setMasksToBounds:YES];
    [buttonLayer setCornerRadius:5.0];
    [buttonLayer setBorderWidth:1.0f];
    [buttonLayer setBorderColor:[UIColor colorWithRed:153.0f / 255.0f green:153.0f / 255.0f blue:153.0f / 255.0f alpha:1.0f].CGColor];

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    [gradientLayer setBounds:self.bounds];
    NSArray *colors = [NSArray arrayWithObjects:
            (id) [UIColor colorWithRed:129.0f / 255.0f green:151.0f / 255.0f blue:179.0f / 255.0f alpha:0.8f].CGColor, // top
            (id) [UIColor colorWithRed:111.0f / 245.0f green:133.0f / 255.0f blue:162.0f / 255.0f alpha:0.4f].CGColor, // center
            (id) [UIColor colorWithRed:95.0f / 245.0f green:118.0f / 255.0f blue:151.0f / 255.0f alpha:0.4f].CGColor, // center
            (id) [UIColor colorWithRed:75.0f / 245.0f green:99.0f / 255.0f blue:133.0f / 255.0f alpha:0.8f].CGColor, // bottom
            nil];

    [gradientLayer setPosition:CGPointMake([self bounds].size.width / 2, [self bounds].size.height / 2)];
    [gradientLayer setColors:colors];
    [buttonLayer insertSublayer:gradientLayer atIndex:0];

    [self setTitleColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f] forState:UIControlStateNormal];
    [self setTintColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.3f]];
}

最佳答案

看起来渐变层均匀地分隔了颜色。这就是为什么你会得到你正在得到的效果。

要解决此问题,您可以使用 CAGradientLayerlocations 属性。

像这样...

gradientLayer.locations = @[@0, @0.5, @0.5, @1.0];

TBH,使用 UIButton 执行此操作的最简单方法是使用图像。

只需创建一个具有所需渐变和边框的按钮图像,然后将其添加为背景图像即可。

如果您需要以不同尺寸使用它,您可以创建可调整大小的图像。

关于ios - 如何为 UIButton 设置自定义渐变背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19775936/

相关文章:

ios - 如何在 PageViewController 中将 CGGradients 混合在一起?

firefox - Firefox 3.5 的 CSS 渐变

ios - 使用字典 swift 发布参数以切断

ios - 我应该在关闭 View 之前关闭键盘吗?

swift - swift4 中用于淡出动画的 UIButton 扩展中的内存泄漏

ios - 单击 UIButton Swift 更改 View Controller (无 Storyboard )

python - 梯度下降运行时错误

iOS:与 UIButton 的 UIControlEventTouchUpOutside 事件的行为不一致

ios - 当应用程序在后台时从信标接收信号

ios - 具有透明图像背景的 UIButton 未绘制透明