矩形中的SwiftUI对角线LinearGradient [英] SwiftUI diagonal LinearGradient in a rectangle
问题描述
问题:我正在尝试在SwiftUI中以矩形绘制对角线性渐变.
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.
代码:
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:
代码:
struct BrandGradient_Previews: PreviewProvider {
static var previews: some View {
BrandGradient()
.frame(width: 300, height: 300)
}
}
但是,如果我将预览框架更改为 .frame(width:300,height:100)
,则会错误地呈现(IMO):
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).
我将您的疑虑带到了 Adobe XD
和 Photoshop
之类的专业工具上,结果与 xCode
相同,我只是在发布 Adobe XD
结果,您实际上可以在线或离线在任何梯度生成器上运行相同的测试.
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.
希望这会有所帮助.
这篇关于矩形中的SwiftUI对角线LinearGradient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!