Compositing Group —— SwiftUI中的防止子视图继承修饰符的方法

Compositing Group —— SwiftUI中的防止子视图继承修饰符的方法,第1张

Compositing Group —— SwiftUI中的防止子视图继承修饰符的方法

概述:
在使用Material时,经常会遇到子视图继承了父视图阴影的情况,如下图所示,字体的边缘也是有阴影的。之前我一直用 .cornerRadius(_) 来避免这种继承发生,但是毕竟它本身是用来裁切视图的。今天突然发现一个.compositingGroup(),很好用!但是苹果文档看半天没明白(样例也太奇怪了)。所以写了这篇文章。

Apple Documentation

A compositing group makes compositing effects in this view’s ancestor views, such as opacity and the blend mode, take effect before this view is rendered.
Use compositingGroup() to apply effects to a parent view before applying effects to this view.

Compositing Group 向本视图的父视图进行复合效果,比如不透明度或者渲染模式,这些效果会在本视图渲染前生效。
在给本视图添加效果前,使用comspsitingGroup给本视图的父视图提供视图效果

In the example below the compositingGroup() modifier separates the application of effects into stages. It applies the opacity(_😃 effect to the VStack before the blur(radius:) effect is applied to the views inside the enclosed ZStack. This limits the scope of the opacity change to the outermost view.

在下面的样例中,使用compositingGroup修饰符,分阶段应用视觉效果。它首先将opacity效果应用到Vstack,之后向ZStack里面的视图添加blur的效果。这样就将不透明度的效果限制在最外面的视图

VStack {
    ZStack {
        Text("CompositingGroup")
            .foregroundColor(.black)
            .padding(20)
            .background(Color.red)
        Text("CompositingGroup")
            .blur(radius: 2)
    }
    .font(.largeTitle)
    .compositingGroup()
    .opacity(0.9)
}

具体效果见苹果官方文档翻译完还是觉得很一头雾水,直接看样例吧


样例

下面的代码是最底下的视图,没有应用不透明度的效果

ZStack{
    Rectangle().frame(width: 50, height: 50, alignment: .center).foregroundStyle(.yellow)
    
    Rectangle().offset(x: 10, y: 10).frame(width: 50, height: 50, alignment: .center).foregroundStyle(.green)
    
    Rectangle().offset(x: 20, y: 20).frame(width: 50, height: 50, alignment: .center).foregroundStyle(.blue)
}.padding().background(.red)

在代码后加入 .opacity(0.5) 得到最上面的视图。可以看到视图的所有颜色都变得透明了,而且重叠部分存在透视的混合效果,说明不透明度的效果应用到了每个子视图,之后再将它们组合起来。
如果向代码后添加.compositingGroup().opacity(0.5) 则会得到中间的视图,可以看到所有的颜色是依旧透明,但是重叠部分没有透视效果。可以理解为,首先把他们组合起来,看作一个视图,之后再将 不透明度 应用到这个组合在一起的视图中。


应用

将视图组合起来在使用.shadow(_),就可以把视图作为一个整体应用阴影效果,不用担心每次用material之后使用阴影都会继承到子视图。代码和效果图如下。

        Text("Hello, World!")
            //mfont是我自己定义的自定义字体函数,把它视作.font()即可
            .mfont(size:.bannerBody)
            .padding()
            .background(.bar,in:Capsule())
            .shadow(radius: 3)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/996759.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存