Код: Выделить всё
struct ContentView: View {
private let textLine1 = "The quick brown fox"
private let textLine2 = "jumps over the lazy dog"
private let paddingSize: CGFloat = 4
private var textBackground: some View {
Canvas { ctx, size in
let resolvedText1 = ctx.resolve(Text(textLine1))
let resolvedText2 = ctx.resolve(Text(textLine2))
let sizeText1 = resolvedText1.measure(in: size)
let sizeText2 = resolvedText2.measure(in: size)
let outlineText1 = Path(
roundedRect: CGRect(
x: ((size.width - sizeText1.width) / 2) - paddingSize,
y: ((size.height / 2) - sizeText1.height) - paddingSize,
width: sizeText1.width + (2 * paddingSize),
height: sizeText1.height + (2 * paddingSize)
),
cornerRadius: 4
)
let outlineText2 = Path(
roundedRect: CGRect(
x: ((size.width - sizeText2.width) / 2) - paddingSize,
y: (size.height / 2) - paddingSize,
width: sizeText2.width + (2 * paddingSize),
height: sizeText2.height + (2 * paddingSize)
),
cornerRadius: 4
)
let combinedOutline = outlineText1.union(outlineText2)
ctx.fill(combinedOutline, with: .color(white: 0.4, opacity: 0.4))
ctx.stroke(combinedOutline, with: .foreground, lineWidth: 2)
}
}
var body: some View {
ZStack {
textBackground
VStack(spacing: 0) {
Text(textLine1)
Text(textLine2)
}
}
.font(.title2)
}
}
struct MyTextBackground: Shape {
let text1: String
let text2: String
func path(in rect: CGRect) -> Path {
var path = Path()
//let ctx = GraphicsContext(path) // Error: 'GraphicsContext' cannot be constructed because it has no accessible initializers
// Help - how do I find the size of the text??
return path
}
}
< /code>
Такая форма может быть заполнена и поглажена легко. Материал также будет простым, вместо того, чтобы использовать (довольно запутанные) обходные пути, которые были предложены в качестве ответов на пост, упомянутый выше:
Код: Выделить всё
ZStack {
MyTextBackground(text1: textLine1, text2: textLine2)
.fill(.ultraThinMaterial)
.stroke(.primary, lineWidth: 2)
VStack(spacing: 0) {
// ...
}
}
.font(.title2)
Подробнее здесь: https://stackoverflow.com/questions/785 ... stom-shape
Мобильная версия