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:

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):

How can I get the gradient to render from corner to corner in a rectangle as well as a square?
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.

Hope this helps a bit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With