Ios 如何为UIButton设置自定义渐变背景?
我想创建一个自定义的UIButton渐变背景。我附上了一些关于要求的图片。Ios 如何为UIButton设置自定义渐变背景?,ios,uibutton,gradient,cagradientlayer,Ios,Uibutton,Gradient,Cagradientlayer,我想创建一个自定义的UIButton渐变背景。我附上了一些关于要求的图片。 但我的渐变背景不是我想象的那样 我的问题是如何设置梯度的位置?(从顶部到中心,然后从中心到底部) 这是我的密码: - (void)setBlueShiningLayer { CALayer *buttonLayer = self.layer; [buttonLayer setMasksToBounds:YES]; [buttonLayer setCornerRadius:5.0];
但我的渐变背景不是我想象的那样 我的问题是如何设置梯度的位置?(从顶部到中心,然后从中心到底部) 这是我的密码:
- (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]];
}
看起来渐变层将颜色均匀地隔开。这就是为什么你得到了你得到的效果 要解决此问题,您可以使用
CAGradientLayer
的locations
属性
像这样
gradientLayer.locations = @[@0, @0.5, @0.5, @1.0];
TBH,使用ui按钮执行此操作的最简单方法是使用图像
只需创建一个带有渐变和边框的按钮图像,然后将其添加到背景图像中
如果需要以不同的大小使用图像,可以创建可调整大小的图像。Swift-Version4.2
@IBOutlet weak var gButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let topGradientColor = UIColor.red
let bottomGradientColor = UIColor.yellow
let gradientLayer = CAGradientLayer()
gradientLayer.frame = gButton.bounds
gradientLayer.colors = [topGradientColor.cgColor, bottomGradientColor.cgColor]
//Vertical
//gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
//gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
//Horizontal
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
gradientLayer.locations = [0.0, 1.0]
gButton.layer.insertSublayer(gradientLayer, at: 0)
}
我的回答对你的问题有帮助吗?非常感谢,现在可以了,但我也必须将最后一个位置设置为0。我同意你使用图像,但设计师给我的是RGB而不是图片:)