I'm using a drag gesture to change the Hue/Saturation of a Color object. The idea is that you can drag across the screen and see all Hue values (0.0 - 1.0), and the same top to bottom with Saturation.
I require the size of the Screen (or view, this is a single view app) in order to normalize/convert the CGPoint values into a range between 0.0 - 1.0, but I am unable to find anyway to get this information. There are many threads discussing this, but they usually talk about how to set the width/heigh of a View when I just want to retrieve it.
I have everything functioning, just that I am using hardcoded values to normalize it.
Look into GeometryReader. It allows you to get the size of the current view:
struct ContentView: View {
var body: some View {
GeometryReader { geo in
VStack {
Text("Hello World!")
Text("Size: (\(geo.size.width), \(geo.size.height))")
}
}
}
}
And here is an example where you can drag on the screen to change the hue value:
struct ContentView: View {
@State private var hue: CGFloat = 0
var body: some View {
GeometryReader { geo in
ZStack {
Color.white
.gesture(DragGesture().onChanged({ value in
self.hue = value.location.y / geo.size.height
}))
VStack {
Text("Hello World!")
Text("Size: (\(geo.size.width), \(geo.size.height))")
Text("Hue: \(self.hue)")
}.allowsHitTesting(false)
}
}
.edgesIgnoringSafeArea(.all)
}
}
GeometryReader
breaking your view layout? Check out this gist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With