【问题标题】:Change opacity of UIColor in SwiftUI View在 SwiftUI 视图中更改 UIColor 的不透明度
【发布时间】:2021-05-20 02:53:06
【问题描述】:

我添加了一个带有不透明度的颜色资源,并尝试在 SwiftUI 视图中使用它,例如 .foregroundColor(Color("customAlertColor").opacity(0.3)),但无论我将其设置为什么值,设置不透明度都没有任何效果。

我也尝试使用像.foregroundColor(Color(.sRGB, red: 242/255, green: 242/255, blue: 242/255, opacity: 0.2)) 这样的 rgb 值来设置颜色,但它也没有帮助。

如果我更改其中一种系统颜色的不透明度,例如 .foregroundColor(.blue.opacity(0.8)),它可以完美地反映更改。

我是否需要以不同的方式设置 UIColor 以使不透明度与 SwiftUI 视图一起使用?

【问题讨论】:

  • 您尝试在什么观点上应用这个?它适用于Text
  • 为什么要除以 255?颜色通道不再是 8 位了。
  • @Jessy 参数标签采用values from 0 to 1
  • @aheze 除法运算不是问题。将输入表示为 0-255 是个问题,而除法只是顺其自然。
  • @aheze 不,这仅适用于低于 10 的 iOS。在为 iOS 10 或更高版本链接的应用程序上,颜色是在扩展的颜色空间中指定的,并且输入值永远不会被限制。 developer.apple.com/documentation/uikit/uicolor/1621925-init

标签: swift swiftui


【解决方案1】:

在 macos 11.4、xcode 12.5、target ios 14.5 和 macCatalyst 11.3 上,以下测试代码对我来说一切正常。我想肯定有一些其他代码(或设置)会影响结果。这个测试对你有用吗?

import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
struct ContentView: View {
    var body: some View {
        Rectangle()
            .foregroundColor(Color("customAlertColor").opacity(0.3))
          //  .foregroundColor(Color(red: 49/255, green: 163/255, blue: 159/255).opacity(0.3))
          //  .foregroundColor(Color(.sRGB, red: 49/255, green: 163/255, blue: 159/255, opacity: 0.3))
    }
}

【讨论】:

    猜你喜欢
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2012-07-18
    • 1970-01-01
    • 2013-03-04
    • 2013-01-06
    相关资源
    最近更新 更多