[英]Mask rectangle with a text in SwiftUI
I want to achieve following using SwiftUI:我想使用 SwiftUI 实现以下目标:
This is what I have tried:这是我尝试过的:
Text("test").mask(Rectangle().frame(width: 200, height: 100).foregroundColor(.white))
Also the other way around:反之亦然:
Rectangle().frame(width: 200, height: 100).foregroundColor(.white).mask(Text("test"))
Both of those samples gave me the inverse result of what I wanted.这两个样本都给了我想要的结果。 Meaning that only the text was showing in white with the rectangle being "masked away".这意味着只有文本显示为白色,矩形被“屏蔽”。
I also thought of the alternative where I simply combine Text
and Rectangle
in a ZStack
.我还想到了在ZStack
中简单地结合Text
和Rectangle
的替代方案。 The rectangle having the foreground color and the text the background color.具有前景色的矩形和具有背景色的文本。 This would result in the same effect.这将产生相同的效果。 However I don't want to do this as this seems like a hack to me.但是我不想这样做,因为这对我来说似乎是一种黑客行为。 For instance if I want to add a gradient or an image to the background this method wouldn't work very well.例如,如果我想在背景中添加渐变或图像,则此方法效果不佳。
Is there a good way on how to do this in SwiftUI?在 SwiftUI 中如何做到这一点有什么好的方法吗? I wouldn't mind if it is through a UIViewRepresentable
.我不介意它是否通过UIViewRepresentable
。
Actually, even if it may seems like an hack to you, it's how SwiftUI works.实际上,即使它对您来说似乎是一个 hack,这就是 SwiftUI 的工作原理。
You can avoid this "hack" by creating a custom view您可以通过创建自定义视图来避免这种“黑客攻击”
An example could be:一个例子可能是:
public struct BackgroundedText: View {
var first_color = Color.green
var second_color = Color.white
var text_color = Color.green
var size = CGSize(width: 200, height: 100)
var xOffset: CGFloat = 50
var yOffset: CGFloat = 50
var text = "Hello world!"
init(_ txt: String, _ txt_color: Color, _ fColor: Color, _ sColor: Color, _ size: CGSize, _ xOff: CGFloat, _ yOff: CGFloat) {
self.text = txt
self.text_color = txt_color
self.first_color = fColor
self.second_color = sColor
self.size = size
self.xOffset = xOff
self.yOffset = yOff
}
public var body: some View {
ZStack{
Rectangle()
.frame(width: self.size.width,
height: self.size.height)
.foregroundColor(self.first_color)
Rectangle()
.frame(width: self.size.width - xOffset,
height: self.size.height - yOffset)
.foregroundColor(self.second_color)
Text(self.text)
.foregroundColor(self.text_color)
}
}
}
So you can use the view in this way:所以你可以这样使用视图:
struct ContentView: View {
var body: some View {
BackgroundedText("Hello", .green, .green, .white, CGSize(width: 200, height: 100), 50, 50)
}
}
If you want, you can make the rectangle resize based on text inside如果你愿意,你可以根据里面的文字调整矩形的大小
Please refer to this anwser first, and then you'll understand the following code I made:请先参考this anwser ,然后您将了解我制作的以下代码:
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
var body: some View {
// text used in mask
let text = Text("Text")
.font(.system(size: 80, weight: .black, design: .rounded))
.scaledToFit() // center text in view
// container
return ZStack {
// background color
Color.white.grayscale(0.3)
// text card
Gradient.diagonal(.yellow, .green) // my custom extension
.inverseMask(text) // ⭐️ inverse mask
// shadow for text
.shadow(color: Color.black.opacity(0.7), radius: 3, x: 3, y: 3)
.frame(width: 300, height: 200)
// highlight & shadow
.shadow(color: Color.white.opacity(0.9), radius: 18, x: -18, y: -18)
.shadow(color: Color.black.opacity(0.3), radius: 14, x: 14, y: 14)
}
}
}
PlaygroundPage.current.setLiveView(ContentView())
and the result is:结果是:
The key extension used in the above code is .inverseMask()
:上述代码中使用的关键扩展名是.inverseMask()
:
import SwiftUI
extension View {
// view.inverseMask(_:)
public func inverseMask<M: View>(_ mask: M) -> some View {
// exchange foreground and background
let inversed = mask
.foregroundColor(.black) // hide foreground
.background(Color.white) // let the background stand out
.compositingGroup() // ⭐️ composite all layers
.luminanceToAlpha() // ⭐️ turn luminance into alpha (opacity)
return self.mask(inversed)
}
}
----[Edited]----- ----[已编辑]-----
My custom extension for Gradient
:我的Gradient
自定义扩展:
import SwiftUI
extension Gradient {
// general linear gradient ---------------------------
public static func linear(
from start: UnitPoint,
to end: UnitPoint,
colors : [Color] // use array
) -> LinearGradient
{
LinearGradient(
gradient : Gradient(colors: colors),
startPoint: start,
endPoint : end
)
}
public static func linear(
from start: UnitPoint,
to end: UnitPoint,
colors : Color... // use variadic parameter
) -> LinearGradient
{
linear(from: start, to: end, colors: colors)
}
// specialized linear gradients ------------------------
// top to bottom
public static func vertical(_ colors: Color...) -> LinearGradient {
linear(from: .top, to: .bottom, colors: colors)
}
// leading to trailing
public static func horizontal(_ colors: Color...) -> LinearGradient {
linear(from: .leading, to: .trailing, colors: colors)
}
// top leading to bottom trailing
public static func diagonal(_ colors: Color...) -> LinearGradient {
linear(from: .topLeading, to: .bottomTrailing, colors: colors)
}
// top leading to bottom trailing
public static func diagonal2(_ colors: Color...) -> LinearGradient {
linear(from: .bottomLeading, to: .topTrailing, colors: colors)
}
}
I had a similar requirement.我有类似的要求。 Actually my requirement was that the text is a multiline text that scrolls up to reveal one line at a time ( timed with someone narrating the text. The background was an image.实际上,我的要求是文本是多行文本,可以向上滚动以一次显示一行(与某人叙述文本时间同步。背景是图像。
I solved it the following way.我通过以下方式解决了它。 A ZStack with the image first, then the Text layer with the multiline text positioned the way I want it, and then another layer of the image with a rectangular hole made where I want the text to appear through.首先是带有图像的 ZStack,然后是带有多行文本的文本层,其位置按我想要的方式放置,然后是另一层带有矩形孔的图像,在我希望文本出现的位置出现。 The approach may meet your needs - you will need to position the hole, change colors etc. to meet your needs.该方法可能会满足您的需求——您需要将 position 孔、更改 colors 等来满足您的需求。 The code shows a rectangle hole about three quarters of the way down the image.该代码在图像下方大约四分之三处显示了一个矩形孔。
struct TestView : View {
var body: some View {
GeometryReader { proxy in
ZStack {
Image("MyImage")
.resizable()
.scaledToFit()
Text("Multiline\ntext\nfor\nscrolling")
.font(.title).foregroundColor(.white)
.position(x: proxy.size.width * 0.5, y: proxy.size.height * 0.75 )
Image("MyImage")
.resizable()
.scaledToFit()
.mask(self.makeMask(for: proxy.size))
}
}
}
func makeMask(for sz : CGSize) -> some View {
return VStack(spacing: 0) {
Rectangle().fill(Color.black)
.frame(height: sz.height * 0.75 + 4)
Rectangle().fill(Color.clear)
.frame(height: 40)
Rectangle().fill(Color.black)
.frame(height: sz.height * 0.25 - 40)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.