SwiftUI Shape的阴影偏移

时间:2019-10-20 06:38:53

标签: ios graphics swiftui

我正在尝试使用Shape,Geometry阅读器和Path在SwiftUI中绘制一个圆,我希望阴影位于圆的正下方,但是阴影会偏移,而我似乎无法将其绘制在哪里它应该:

shadow offset problem


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
    }
}




1 个答案:

答案 0 :(得分:0)

好,所以我似乎已经设法解决了这个问题。宽度/高度与代码交互作用以计算阴影的位置-阴影位置似乎来自框架尺寸而不是形状,

添加

.aspectRatio(contentMode: .fit)

解决了问题

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

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

在我看来就像一个错误,但这可以解决此问题:

enter image description here

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
    }
}