I am trying to implement a magnification gesture in a SwiftUI RealityView
. My goal is to allow users to zoom into a RealityKit scene by pinching. However, the MagnifyGesture
does not seem to have any effect. Below is my current implementation:
import SwiftUI
import RealityKit
struct ContentView: View {
@State private var scale: Float = 1.0
@GestureState private var magnifyBy = 1.0
var magnification: some Gesture {
MagnifyGesture()
.targetedToAnyEntity()
.updating($magnifyBy) { value, gestureState, transaction in
gestureState = value.magnification
}
}
var body: some View {
VStack {
RealityView { content in
// Load and Add Your RealityKit Scene (Without Anchor)
if let sceneEntity = try? await Entity(named: "Scene", in: realityKitContentBundle) {
content.add(sceneEntity) // Directly add to content
}
// Add the initial RealityKit content
let dataPoints = loadData()
for dataPoint in dataPoints {
let sphere = createSphereEntity()
sphere.position = SIMD3(dataPoint.x, dataPoint.y, dataPoint.z)
content.add(sphere)
}
}
.gesture(magnification)
.scaleEffect(magnifyBy)
// Display the current scale
Text("Current Scale: (magnifyBy, specifier: "%.2f")")
.padding()
}
}
func loadData() -> [SIMD3<Float>] {
// Example function to load data points
return [SIMD3(0, 0, 0), SIMD3(1, 1, 1)]
}
func createSphereEntity() -> Entity {
// Example function to create a sphere entity
return Entity()
}
}
Issues:
- The
MagnifyGesture
does not seem to affect the scale of theRealityView
. - The
scaleEffect(magnifyBy)
modifier does not apply the magnification correctly.
Question:
How can I get the MagnifyGesture
to work correctly within a RealityView
in SwiftUI? Are there any specific considerations or additional steps needed to apply gestures to RealityView
content?
Any help or guidance would be greatly appreciated!
What did you try and what were you expecting?
I expected the MagnifyGesture
to allow users to zoom into the RealityView
content by pinching. I have tried:
- Ensured that the
RealityView
and its content are properly set up and rendering correctly. - Applying the gesture to a 2D SwiftUI element like
Circle()
, which works correctly.
However, the magnification does not affect the RealityView
. The magnifyBy
state does not change when the gesture is applied to the RealityView
, but it works as expected when applied to a 2D SwiftUI element like Circle()
.
bcc_jh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.