gpt4 book ai didi

swiftui - SwiftUI 中的自定义交叉影线背景形状或 View

转载 作者:行者123 更新时间:2023-12-05 01:11:28 26 4
gpt4 key购买 nike

我正在尝试创建阴影交叉影线。但到目前为止,我可以通过添加图像来完成。

如何创建一个自定义 View ,其中将绘制线条而不用图像填充?

import SwiftUI

struct ContentView: View {

var body: some View {
ZStack {
Image("lineFilledBG").resizable().clipShape(Circle())
Circle().stroke()
Circle().foregroundColor(.yellow).opacity(0.3)
}
}
}


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

现在是这样的。想要在另一个 View 或形状之上绘制线条,而不添加不透明度和图像图案填充。

Cross-hatched shape

最佳答案

感谢 Cenk Bilgen为条纹图案。稍作调整,以便您可以旋转任何形状的舱口。

import SwiftUI
import CoreImage.CIFilterBuiltins

extension CGImage {

static func generateStripePattern(
colors: (UIColor, UIColor) = (.clear, .black),
width: CGFloat = 6,
ratio: CGFloat = 1) -> CGImage? {

let context = CIContext()
let stripes = CIFilter.stripesGenerator()
stripes.color0 = CIColor(color: colors.0)
stripes.color1 = CIColor(color: colors.1)
stripes.width = Float(width)
stripes.center = CGPoint(x: 1-width*ratio, y: 0)
let size = CGSize(width: width, height: 1)

guard
let stripesImage = stripes.outputImage,
let image = context.createCGImage(stripesImage, from: CGRect(origin: .zero, size: size))
else { return nil }
return image
}
}

extension Shape {

func stripes(angle: Double = 45) -> AnyView {
guard
let stripePattern = CGImage.generateStripePattern()
else { return AnyView(self)}

return AnyView(Rectangle().fill(ImagePaint(
image: Image(decorative: stripePattern, scale: 1.0)))
.scaleEffect(2)
.rotationEffect(.degrees(angle))
.clipShape(self))
}
}

及用法

struct ContentView: View {

var body: some View {
VStack {
Rectangle()
.stripes(angle: 30)
Circle().stripes()
Capsule().stripes(angle: 90)
}
}
}

Output image link

关于swiftui - SwiftUI 中的自定义交叉影线背景形状或 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63130755/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com