swiftui

How to apply a dot matrix filter to an image in SwiftUI


I want to achieve the dot matrix style effect that you see on ticker displays in stock exchanges, airports etc. how can i apply this effect to my image in swiftui

struct ContentView: View {
    var body: some View {
        Image(.bitcoin)
    }
}

This is the effect that i want for my image:

enter image description here


Solution

  • A metal shader like this could work,

    // put this in a file called Shaders.metal
    #include <metal_stdlib>
    using namespace metal;
    
    [[ stitchable ]] half4 dotMatrix(float2 position, half4 color) {
        if (int(position.x) % 6 < 3 && int(position.y) % 6 < 3) {
            return color;
        } else {
            return half4(0, 0, 0, 0);
        }
    }
    

    The idea is to put transparent color at any position where x % 6 >= 3 or y % 6 >= 3. You can adjust the size of the dots and the distance between them by changing 6 and 3.

    Usage in SwiftUI:

    Image("some image")
        .colorEffect(Shader(
            function: .init(library: .default, name: "dotMatrix"),
            arguments: []
        ))
    

    Output for a simple capsule shape:

    enter image description here

    For a more circular shape, you can use a condition like this:

    if (
        pow((round(position.x / 10) - position.x / 10), 2) +
        pow((round(position.y / 10)  - position.y / 10), 2) < 0.1
    )
    

    10 and 0.1 are parameters you can adjust.