SwiftUI形状的阴影偏移量

3

我正在尝试使用Shape、Geometry reader和Path在SwiftUI中绘制一个圆形,我希望阴影正好位于圆形下方,但阴影偏移了,并且我似乎无法将它绘制到应该处:

阴影偏移问题


struct ContentView: View {

    var body: some View {

         return  GeometryReader { geometry in

            VStack(alignment: .center) {
            BackgroundRing()
                .stroke(Color.red, style:  StrokeStyle(lineWidth: geometry.size.width < geometry.size.height ? geometry.size.width / 12.0 :  geometry.size.height / 12))
                .padding()
                .shadow(color: .gray, radius: 1.0, x: 0.0, y: 0.0)
            }
         }
    }
}

struct BackgroundRing : Shape {
     func path(in rect: CGRect) -> Path {
        var path: Path = Path()

                let radiusOfRing: CGFloat = (rect.width < rect.height ? rect.width/2 - rect.width / 12 : rect.height/2 - rect.height / 12)
        path.addRelativeArc(center: CGPoint(x: rect.width/2, y: rect.height/2),
                                radius: radiusOfRing,
                                startAngle: Angle(radians: 0.0),
                                delta: Angle(radians: Double.pi * 2.0 ))

        return path
    }
}





为什么不只是一个阴影? - Mojtaba Hosseini
没有任何区别-结果完全相同。我设置了偏移量,试图强制将位置放在路径下方。 - Tomm P
1个回答

6

好的,看起来我似乎成功解决了问题。宽度/高度存在某种与计算阴影位置的代码交互的问题 - 阴影位置似乎是来自框架尺寸而不是形状。

添加

.aspectRatio(contentMode: .fit)

可以解决这个问题。

此外,似乎.shadow自动将默认偏移量设置为与半径相同的值,因此要获得实际偏移量为0.0,您必须将其相对于半径设置,如下所示:

.shadow(radius: 10.0, x: -10.0, y: -10.0)

在我看来这是一个bug,但是这个解决方法可以解决它:

在此输入图片描述

import SwiftUI

struct ContentView: View {

    var body: some View {

         return  GeometryReader { geometry in

            VStack(alignment: .center) {
            BackgroundRing()
               .stroke(Color.red,
                        style:  StrokeStyle(lineWidth: geometry.size.width < geometry.size.height ? geometry.size.width / 12.0 :  geometry.size.height / 12))
                .shadow(radius: 30.0, x: -30.0, y: -30.0)
                .aspectRatio(contentMode: .fit)
            }
         }

    }
}

struct BackgroundRing : Shape {
     func path(in rect: CGRect) -> Path {
        var path: Path = Path()

                let radiusOfRing: CGFloat = (rect.width < rect.height ? rect.width/2 - rect.width / 12 : rect.height/2 - rect.height / 12)
        path.addRelativeArc(center: CGPoint(x: rect.width/2, y: rect.height/2), // <- this change solved the problem
                                radius: radiusOfRing,
                                startAngle: Angle(radians: 0.0),
                                delta: Angle(radians: Double.pi * 2.0 ))

        return path
    }
}


我发现另一个自定义形状也有同样的 bug,但只有水平偏移。你的解决方案很好,但对我没有帮助。 - Vyacheslav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接