Magnify Gesture

Using the MagnifyGesture to scale entities.

Let’s start with a basic example of using the MagnifyGesture gesture to scale an entity, while clamping the value.

struct Example008: View {
    var body: some View {
        RealityView { content in
            // Load the scene from the Reality Kit bundle
            if let scene = try? await Entity(named: "GestureLabs", in: realityKitContentBundle) {
                content.add(scene)

                // Lower the entire scene to the bottom of the volume
                scene.position.y = -0.4
            }
        }
        .gesture(magnifyGesture)
    }

    var magnifyGesture: some Gesture {
        MagnifyGesture()
            .targetedToAnyEntity()
            .onChanged { value in

                // Get the magnification from the gesture
                let scaler = Float(value.magnification)

                // Clamp the value so it can't get too small or too large
                let minScale: Float = 0.25
                let maxScale: Float = 3
                let clampedScale = min(Float(max(Float(scaler), minScale)), maxScale)

                // Apply the new scale
                value.entity
                    .setScale(
                        .init(repeating: clampedScale),
                        relativeTo: value.entity.parent!
                    )

            }
    }
}

Issue: This doesn’t take into account the initial scale of the entity. If the entity starts at a scale of anything other than 1, you will see it “snap” to the starting scale of the gesture. Learn how to fix this in Improved Magnify Gesture.

Download the Xcode project with this and many more examples from Step Into Vision.

Some examples are provided as standalone Xcode projects. You can find those here.

Questions or feedback?