繁体   English   中英

如何在 SwiftUI 中的形状笔划上应用内阴影?

[英]How to apply inner shadow on stroke of a shape in SwiftUI?

我想在形状的笔划上应用内阴影。 我找到了一个处理内部阴影的函数(还不能使用 iOS 16),但是我很难尝试将此函数应用于笔画本身。

这是我得到的:

struct ContentView: View {
    var body: some View {
        VStack {
            PolygonShape(sides: 7)
                .stroke(Color.white, lineWidth: 10)
            PolygonShape(sides: 7)
                .innerShadow(color: .red, radius: 10)
        }
        .padding(32)
        .background(Color.black.ignoresSafeArea())
    }
}

extension Shape {
    func innerShadow(color: Color, radius: Double) -> some View {
        overlay(
            stroke(color, lineWidth: radius)
                .blur(radius: radius)
                .mask(self)
        )
    }
}

struct PolygonShape: Shape {
    let sides: Int

    func path(in rect: CGRect) -> Path {
        let c = CGPoint(x: rect.width/2.0, y: rect.height/2.0)
        let r = Double(min(rect.width,rect.height)) / 2.0
        var vertices:[CGPoint] = []
        for i in 0...sides {
            let angle = (2.0 * Double.pi * Double(i)/Double(sides))
            let pt = CGPoint(x: r * cos(angle), y: r * sin(angle))
            vertices.append(CGPoint(x: pt.x + c.x, y: pt.y + c.y))
        }
        var path = Path()
        for (n, pt) in vertices.enumerated() {
            n == 0 ? path.move(to: pt) : path.addLine(to: pt)
        }
        path.closeSubpath()
        return path
    }
}

struct StackedElementsView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

这就是它的样子,但不是我想要的:

在此处输入图像描述

我想做的是将内部红色阴影放在白色笔划本身上,因此笔划中只有红色阴影,形状中没有。

与此类似的东西:

在此处输入图像描述

我尝试在颜色本身上应用内部阴影,但由于它不是一个形状,它没有编译: .stroke(Color.white.innerShadow(color: .red, radius: 2)

如何在描边颜色上应用内阴影?

这不是最干净或最完整的答案,但它很简单。

以下代码,在您的var body中...

ZStack {
                
    PolygonShape(sides: 7)
        .stroke(Color.white, lineWidth: 10)
                
    PolygonShape(sides: 7)
        .stroke(Color.black, lineWidth: 10)
        .scaleEffect(1.07)
        .shadow(color: .red, radius: 3)
                
    PolygonShape(sides: 7)
        .scaleEffect(0.965)
        .shadow(color: .red, radius: 3)
}

...产生这种类型的边框:

不过,形状周围有一条红线,这可能是也可能不是一个简单的修复,具体取决于您的情况。 只是把它作为一个临时答案:) 或者,如果你可以让形状只是边框(没有填充),你可以使用.mask并将它的蒙版为你选择的渐变。

虽然不是完美的并且可能无法处理很多情况,但另一种方法是绘制笔划,然后是其中一半大小的另一笔划模糊:

extension Shape {
    func stroke<Stroke: ShapeStyle>(
        _ content: Stroke,
        lineWidth: Double = 1,
        innerShadow: (color: Color, radius: Double)
    ) -> some View {
        stroke(content, lineWidth: lineWidth / 2)
            .blur(radius: innerShadow.radius)
            .background(stroke(innerShadow.color, lineWidth: lineWidth))
    }
}
PolygonShape(sides: 7)
    .stroke(Color.white, lineWidth: 10, innerShadow: (Color.red, 2))

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM