Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI diagonal LinearGradient in a rectangle

Problem: I'm trying to render a diagonal linear gradient in a rectangle shape in SwiftUI.

I implemented a standard multi stop linear gradient, and it works perfectly when rendered as a square, however when I change the frame to a rectangle, it has some odd behaviour, and appears to look more horizontal, or have some strange clipping.

Code:

struct CustomGradient: View {

    var body: some View {
        LinearGradient(
            gradient: Gradient(stops: [
                .init(color: Color(#colorLiteral(red: 0.776, green: 0.266, blue: 0.988, alpha: 1)), location: 0),
                .init(color: Color(#colorLiteral(red: 0.356, green: 0.348, blue: 0.870, alpha: 1)), location: 0.62),
                .init(color: Color(#colorLiteral(red: 0.357, green: 0.349, blue: 0.870, alpha: 1)), location: 1)
            ]),
            startPoint: .bottomTrailing,
            endPoint: .topLeading
        )
    }

If I render the preview as a square, it works fine Preview: enter image description here

Code:

struct BrandGradient_Previews: PreviewProvider {
    static var previews: some View {
        BrandGradient()
            .frame(width: 300, height: 300)
    }
}

However, if I change the preview frame to .frame(width: 300, height: 100), it renders incorrectly (IMO): enter image description here

How can I get the gradient to render from corner to corner in a rectangle as well as a square?

like image 852
Jeremy Avatar asked Jul 02 '26 16:07

Jeremy


1 Answers

This is a normal behavior. It's not even a swiftui issue. The problem is that you are stretching the same colors over a smaller height, hence the distribution of color will be much less and hence the purple will not disappear at the edges like it did in the square (It's just there isn't enough space).

I took your concerns to a professional tool such as Adobe XD and Photoshop and the results are the same as xCode I am only posting Adobe XD results, you can really run the same test on any gradient generator online or offline.

enter image description here

Hope this helps a bit.

like image 178
Muhand Jumah Avatar answered Jul 04 '26 13:07

Muhand Jumah