how do you pass a texture to a metal shader in swiftui?

specifically using the newer colorEffect, layerEffect, etc routes. the below does not seem to work. do i have to use the old MTK stuff?

import SwiftUI
import MetalKit

struct HoloPreview: View {
    let startDate = Date()
    @State private var noiseTexture: MTLTexture?

    var body: some View {
        TimelineView(.animation) { context in
            RoundedRectangle(cornerRadius: 20)
                .fill(Color.red)
                .layerEffect(ShaderLibrary.iridescentEffect(
                    .float(startDate.timeIntervalSinceNow),
                    .texture(noiseTexture)
                ), maxSampleOffset: .zero)
        }
        .onAppear {
            noiseTexture = loadTexture(named: "perlinNoiseMap")
        }
    }

    func loadTexture(named imageName: String) -> MTLTexture? {
        guard let device = MTLCreateSystemDefaultDevice(),
              let url = Bundle.main.url(forResource: imageName, withExtension: "png") else {
            return nil
        }

        let textureLoader = MTKTextureLoader(device: device)
        let texture = try? textureLoader.newTexture(URL: url, options: nil)
        return texture
    }
}

#Preview {
    HoloPreview()
}
Answered by DTS Engineer in 803151022

Hello @coratype,

SwiftUI Shaders support Images as shader arguments: https://developer.apple.com/documentation/swiftui/shader/argument/image(_:)

Best regards,

Greg

Accepted Answer

Hello @coratype,

SwiftUI Shaders support Images as shader arguments: https://developer.apple.com/documentation/swiftui/shader/argument/image(_:)

Best regards,

Greg

how do you pass a texture to a metal shader in swiftui?
 
 
Q