在SwiftUI中,如何为UIButton提供渐变,并为按钮提供具有相同渐变的底部阴影?

时间:2019-06-09 18:38:35

标签: swift swiftui ios13

因此,我的一位设计师设计师为我制作了一个密码生成器的模型,我将制作https://imgur.com/gallery/LZNNrWj,但我不知道如何使用SwiftUI(该按钮的渐变)在该渐变中进行编码是#41A5ED->#3099D8,并朝这个方向前进(见图)https://imgur.com/gallery/2rd7Iix,左上方是#41A5ED,右下方是#3099D8。我还想给此按钮一个像https://imgur.com/gallery/gEmBJ1w这样的底部阴影,并使其渐变与按钮相同。如果您对如何执行此操作有任何想法,请让我知道,因为我完全迷路了。

3 个答案:

答案 0 :(得分:0)

您可以这样做:

Button(action: createTask) {
                   Text(“MyButton“)
                       .color(.white)
                       .font(Font.system(size: 17))
                       .frame(height: 56)
                       .frame(minWidth: 0, maxWidth: .infinity)
                       .background(LinearGradient.actionButton, cornerRadius: 28)
                       .shadow() // configure shadow as you want
                   }

为了提高代码的可读性,我分别创建了渐变:

fileprivate extension LinearGradient {
   static let actionButton = LinearGradient(gradient: Gradient(colors: [Color(“ActionGradientFirst”), Color(“ActionGradientSecond”)]),
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing)
}

我在 Assets.xcasset

中声明的颜色ActionGradientFirstActionGradientSecond

答案 1 :(得分:0)

首先使用以下方法创建渐变,

let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.red.cgColor, UIColor.black.cgColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 1, y: 1)
gradientLayer.frame = view.bounds

然后只需将其应用于所需的任何视图,

view.layer.addSublayer(gradientLayer)

要添加阴影,

    let shadowPath = UIBezierPath(rect: view.bounds)
    view.layer.masksToBounds = false
    view.layer.shadowColor = UIColor.grey.cgColor
    view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
    view.layer.shadowOpacity = 0.2
    view.layer.shadowPath = shadowPath.cgPath

答案 2 :(得分:0)

有点晚了,但以防万一它对其他人有帮助。

ZStack{
    LinearGradient(
        gradient: .init(colors: [Color.white, Color.blue.opacity(0.66)]),
        startPoint: .init(x: 0.0, y: 0.0),
        endPoint: .init(x: 0.75, y: 0.75)
    )
    .mask(
        RoundedRectangle(cornerRadius: 15)
            .frame(width: 120, height: 45, alignment: .center)
            .blur(radius: 10)
    )
    .padding(.top, 20)
    Button(action: {}, label: {
        Text("Siguiente")
            .font(.custom("Avenir-Heavy", size: 20))
            .padding(.top, 10)
            .padding(.bottom, 10)
            .padding(.leading, 16)
            .padding(.trailing, 16)
    })
    .foregroundColor(.white)
    .background(
        LinearGradient(
            gradient: .init(colors: [Color.white, Color.blue.opacity(0.75)]),
            startPoint: .init(x: -0.33, y: -0.33),
            endPoint: .init(x: 0.66, y: 0.66)
        ))
    .clipShape(RoundedRectangle(cornerRadius: 15))
    .buttonStyle(PlainButtonStyle())
}
.frame(height: 100)

enter image description here