Skip to content

Instantly share code, notes, and snippets.

@denisenepraunig
Created November 25, 2023 01:45
Show Gist options
  • Save denisenepraunig/fd8d21eaa1cd0a881ca64630bc8ad021 to your computer and use it in GitHub Desktop.
Save denisenepraunig/fd8d21eaa1cd0a881ca64630bc8ad021 to your computer and use it in GitHub Desktop.
SwiftUI Metal Shader changing background color based on mouse position
import SwiftUI
struct ContentView: View {
@State private var hoverLocation: CGPoint = .zero
@State private var isHovering = false
@State var toggleText = false
var body: some View {
ZStack {
Rectangle()
.foregroundStyle(.black)
.layerEffect(ShaderLibrary.circle(
.boundingRect,
.float2(hoverLocation)
), maxSampleOffset: .zero)
.blur(radius: 10.0)
}
.onContinuousHover { phase in
switch phase {
case .active(let location):
hoverLocation = location
isHovering = true
case .ended:
isHovering = false
}
}
.frame(minWidth: 400, idealWidth: 400, maxWidth: .infinity, minHeight: 400, idealHeight: 400, maxHeight: .infinity, alignment: .center)
}
}
#Preview {
ContentView()
}
#include <metal_stdlib>
using namespace metal;
#include <SwiftUI/SwiftUI_Metal.h>
[[ stitchable ]] half4 circle(float2 position, SwiftUI::Layer layer, float4 bounds, float2 touch) {
// Normalized pixel coordinates (from 0 to 1)
float2 st = position/bounds.zw;
// Normalized touch position
float m_x = touch.x / bounds.z;
float m_y = touch.y / bounds.w;
float3 m_color = float3(0.0);
float2 dist = float2(m_x, m_y) - st.xy;
dist.x *= bounds.z/bounds.w;
// Smoothstep draws the circle
// 1.0 - ... to from the black to the desired end-rult
// play around with 0.5 to make the circle smaller or bigger
float mouse_pct = length(dist);
mouse_pct = smoothstep(0.1, 1.0, 1. - mouse_pct * 0.5);
m_color = float3(mouse_pct);
float3 darkPurple = float3(0.28, 0.06, 0.41);
// #15011f
float3 superDarkPurple = float3(0.08, 0.0, 0.12);
return half4(half3(m_color * darkPurple), 1.0);
}
@denisenepraunig
Copy link
Author

Here is the is a very small video of it:

background-shader-moving-hover-super-small.mov

And here is a screenshot:
Screenshot 2023-11-25 at 02 47 59

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment