如何在ios中为按钮提供水平渐变颜色?
我试图在水平方向上给出按钮渐变颜色为蓝色,但没有正确输出。
答案 0 :(得分:0)
我不确定但是试试这段代码
CAGradientLayer *btnGradient = [CAGradientLayer layer];
btnGradient.frame = btn.bounds;
btnGradient.colors = [NSArray arrayWithObjects:
(id)[[UIColor colorWithRed:102.0f / 255.0f green:102.0f / 255.0f blue:102.0f / 255.0f alpha:1.0f] CGColor],
(id)[[UIColor colorWithRed:51.0f / 255.0f green:51.0f / 255.0f blue:51.0f / 255.0f alpha:1.0f] CGColor],
nil];
[yourbtn.layer insertSublayer:btnGradient atIndex:0];
答案 1 :(得分:0)
这将允许您为按钮插入水平渐变,其中第一种颜色在左侧,第二种颜色在右侧:
extension UIView {
func insertHorizontalGradient(_ color1: UIColor, _ color2: UIColor) {
let gradient = CAGradientLayer()
gradient.colors = [color1.cgColor, color2.cgColor]
gradient.transform = CATransform3DMakeRotation(CGFloat.pi / 2, 0, 0, 1)
gradient.frame = bounds
layer.insertSublayer(gradient, at: 0)
}
}
您可能希望保留对图层的引用以调整其框架的大小,否则请务必在按钮框架确定后再调用它。
答案 2 :(得分:-1)
您可以尝试以下代码:
{
UIColor *transBgColor = [UIColor colorWithWhite:1.0 alpha:0.0];
UIColor *black = [UIColor blackColor];
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.opacity = 0.8;
maskLayer.colors = [NSArray arrayWithObjects:(id)black.CGColor,
(id)transBgColor.CGColor, (id)transBgColor.CGColor, (id)black.CGColor, nil];
// Horizontal - commenting these two lines will make the gradient vertical
maskLayer.startPoint = CGPointMake(0.0, 0.5);
maskLayer.endPoint = CGPointMake(1.0, 0.5);
NSNumber *gradTopStart = [NSNumber numberWithFloat:0.0];
NSNumber *gradTopEnd = [NSNumber numberWithFloat:0.4];
NSNumber *gradBottomStart = [NSNumber numberWithFloat:0.6];
NSNumber *gradBottomEnd = [NSNumber numberWithFloat:1.0];
maskLayer.locations = @[gradTopStart, gradTopEnd, gradBottomStart, gradBottomEnd];
maskLayer.bounds = container.bounds;
maskLayer.anchorPoint = CGPointZero;
[container.layer addSublayer:maskLayer];
}