SwiftUI 无法通过 UIColor(patternImage:) 创建颜色

hop*_*opy 5 swift swiftui

我想从图案图像创建颜色对象,但它似乎不起作用:

\n\n
struct ContentView: View {\n\n    var imageColor:Color{\n        let image = UIImage(named: "image_name")!\n        let uiColor = UIColor(patternImage: image)\n        return Color(uiColor)\n    }\n\n    var body: some View {\n        Text("Hello World")\n            .background(imageColor)\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

运行代码,文本背景看起来是透明的。

\n\n

所以我在 lldb 中使用 po 命令来查看 imageColor 到底是什么,我得到了这个:

\n\n
po imageColor\n\xe2\x96\xbf <UIDynamicPatternColor: 0x283b90540; image = <UIImage:0x2809a8090 named(main: bwBlocks2) {509, 300}>>\n\xe2\x96\xbf provider : <ColorBox<UIColor>: 0x283b905c0>\n
Run Code Online (Sandbox Code Playgroud)\n\n

看起来它从图像中创建了正确的颜色,但我在文本背景中看不到它!

\n\n

这是怎么回事?\n图像尺寸有问题吗?\n谢谢;)

\n

Asp*_*eri 3

如果我正确理解你的目标,可以通过以下方式实现

var body: some View {
    Text("Hello World")
        .background(Image("image_name").resizable(resizingMode: .tile))
}
Run Code Online (Sandbox Code Playgroud)