การซูมด้วยการบีบนิ้วและการหมุน
ใช้ PinchGestureHandler และ RotationGestureHandler ร่วมกับการตรวจจับท่าทางพร้อมกัน เพื่อสร้างคอมโพเนนต์รูปภาพที่ซูมและหมุนได้
การซูมด้วยการบีบนิ้วและการหมุน เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Pinch and Rotation Matter
Pinch-to-zoom and rotation are hallmark interactions on mobile, found in photo viewers, maps, and document apps. Implementing them well requires multi-touch gesture recognition that runs on the native thread and smooth real-time transform updates via Reanimated shared values.
React Native Gesture Handler provides Gesture.Pinch() and Gesture.Rotation() recognizers, which combined with Reanimated's useAnimatedStyle and useSharedValue, produce butter-smooth interactions that feel indistinguishable from native implementations.
Gesture.Pinch: Detecting Scale
Gesture.Pinch() recognizes a two-finger pinch or spread gesture. The most important value in the event object is event.scale, which starts at 1.0 when the gesture begins and changes proportionally to finger distance. A value of 2.0 means the fingers are twice as far apart as at start.
You must combine the gesture's incremental scale with a stored base scale to accumulate zoom across multiple pinch gestures — otherwise each new pinch resets to 1.0.
import { Gesture } from 'react-native-gesture-handler';
import { useSharedValue, withSpring } from 'react-native-reanimated';
const scale = useSharedValue(1);
const savedScale = useSharedValue(1);
const pinch = Gesture.Pinch()
.onUpdate((e) => {
scale.value = savedScale.value * e.scale;
})
.onEnd(() => {
savedScale.value = scale.value;
});Clamping Zoom Range
Without clamping, users can zoom in to enormous scales or zoom out until the image disappears. Define a minimum and maximum zoom level and clamp the scale value in the onUpdate callback using a utility worklet.
The clamp function runs on the UI thread as a worklet, keeping the gesture response fast. Choose clamp values appropriate for your content — photo viewers typically allow 1x to 5x zoom, while maps may allow much wider ranges.
const MIN_SCALE = 1;
const MAX_SCALE = 5;
function clamp(value, min, max) {
'worklet';
return Math.min(Math.max(value, min), max);
}
const pinch = Gesture.Pinch()
.onUpdate((e) => {
scale.value = clamp(savedScale.value * e.scale, MIN_SCALE, MAX_SCALE);
})
.onEnd(() => {
savedScale.value = scale.value;
// Snap back if over-zoomed out:
if (scale.value < MIN_SCALE) {
scale.value = withSpring(MIN_SCALE);
savedScale.value = MIN_SCALE;
}
});Gesture.Rotation: Tracking Angle
Gesture.Rotation() tracks the angle change of a two-finger twist gesture. The event.rotation value is in radians — the angle the fingers have rotated from the gesture start position. A full clockwise rotation is approximately 6.28 radians (2π).
Like scale, you must accumulate rotation across multiple gestures by saving the current rotation at gesture end and adding new gesture rotation to the saved offset in subsequent gestures.
const rotation = useSharedValue(0);
const savedRotation = useSharedValue(0);
const rotationGesture = Gesture.Rotation()
.onUpdate((e) => {
rotation.value = savedRotation.value + e.rotation;
})
.onEnd(() => {
savedRotation.value = rotation.value;
});Applying Scale and Rotation in useAnimatedStyle
The transform array in useAnimatedStyle applies both scale and rotation. The order of transforms matters: apply scale first, then rotation (or vice versa depending on desired behavior). React Native's transform array accepts both numeric scale and radian rotation values directly from shared values.
The rotate transform requires a string with the 'rad' suffix, while scale takes a number directly. Use string concatenation (not template literals with backticks) to construct the rotation string in a worklet.
const animatedStyle = useAnimatedStyle(() => ({
transform: [
{ scale: scale.value },
{ rotate: rotation.value + 'rad' }, // concatenate string, no backticks
],
}));
return (
<GestureDetector gesture={composedGesture}>
<Animated.Image
source={{ uri: imageUrl }}
style={[styles.image, animatedStyle]}
/>
</GestureDetector>
);Composing Pinch and Rotation Simultaneously
A photo viewer needs pinch and rotation to work at the same time. Wrap both gestures in Gesture.Simultaneous and pass the composed gesture to a single GestureDetector. This enables the user to zoom and rotate with a two-finger gesture in one fluid motion.
Adding pan simultaneously creates the full photo viewer experience: zoom, rotate, and reposition the image all with two fingers at once.
const composedGesture = Gesture.Simultaneous(
pinch,
rotationGesture,
pan
);
return (
<GestureDetector gesture={composedGesture}>
<Animated.Image
source={{ uri: imageUrl }}
style={[styles.image, animatedStyle]}
resizeMode='contain'
/>
</GestureDetector>
);Double Tap to Reset Zoom
A standard photo viewer feature is double-tapping to toggle between the natural size and a zoomed-in view, and again to reset. Use Gesture.Tap().numberOfTaps(2) for the double-tap recognizer, and in its handler animate scale and rotation back to their initial values with a spring.
Use Gesture.Exclusive with the double-tap gesture having priority over single-tap to prevent single-tap from firing during a double-tap sequence.
const doubleTap = Gesture.Tap()
.numberOfTaps(2)
.onEnd(() => {
if (scale.value > 1) {
// Reset to natural size:
scale.value = withSpring(1);
savedScale.value = 1;
rotation.value = withSpring(0);
savedRotation.value = 0;
offsetX.value = withSpring(0);
offsetY.value = withSpring(0);
} else {
// Zoom to 2x:
scale.value = withSpring(2);
savedScale.value = 2;
}
});Pivot Point for Pinch Zoom
By default the scale transform scales the image from its center point. For a more natural feel, the image should zoom around the focal point — the midpoint between the two fingers. The gesture event provides event.focalX and event.focalY for this purpose.
Implementing focal-point zoom requires adjusting the translation offset alongside scale so the point under the fingers stays fixed during zoom. This math involves calculating the offset change caused by the scale change at a given focal point.
const pinch = Gesture.Pinch()
.onUpdate((e) => {
const newScale = clamp(savedScale.value * e.scale, MIN_SCALE, MAX_SCALE);
const scaleDelta = newScale / scale.value;
// Adjust offset to keep focal point fixed:
offsetX.value = e.focalX - scaleDelta * (e.focalX - offsetX.value);
offsetY.value = e.focalY - scaleDelta * (e.focalY - offsetY.value);
scale.value = newScale;
});Boundary Constraints After Pan and Zoom
After zooming in, the user can pan to see different parts of the image. But you should constrain panning so the image cannot be dragged to reveal empty canvas outside its edges. Calculate the maximum pan offset based on the current scale and image dimensions, and clamp the offset in the pan's onUpdate.
This is the polish that distinguishes a professional photo viewer from a rough prototype. The constraint logic is a few lines of math that run as worklets on the UI thread.
const IMAGE_WIDTH = 300;
const CONTAINER_WIDTH = 375;
const pan = Gesture.Pan()
.onUpdate((e) => {
const maxOffsetX = Math.max(0, (scale.value * IMAGE_WIDTH - CONTAINER_WIDTH) / 2);
offsetX.value = clamp(
savedOffsetX.value + e.translationX,
-maxOffsetX,
maxOffsetX
);
});Animating Back on Over-Zoom
When the user lifts their fingers after over-zooming (below minimum or above maximum), spring the scale back to the limit rather than leaving the image at an unusual size. Do this in the onEnd callback of the pinch gesture.
Similarly, after the user zooms back out to 1x, reset the pan offset to zero so the image returns to center. This combination of boundary checks in onEnd makes the component feel polished and predictable.
const pinch = Gesture.Pinch()
.onEnd(() => {
if (scale.value < MIN_SCALE) {
scale.value = withSpring(MIN_SCALE);
savedScale.value = MIN_SCALE;
// Reset pan to center:
offsetX.value = withSpring(0);
offsetY.value = withSpring(0);
} else if (scale.value > MAX_SCALE) {
scale.value = withSpring(MAX_SCALE);
savedScale.value = MAX_SCALE;
} else {
savedScale.value = scale.value;
}
});Putting It All Together
A complete zoomable, rotatable, pannable photo viewer combines: shared values for scale, rotation, and offset; useAnimatedStyle applying all transforms; Gesture.Simultaneous composing pinch, rotation, pan, and double-tap; and boundary clamping in onUpdate and spring correction in onEnd.
This is one of the most impressive interactions you can build in React Native, and it runs entirely on the UI thread with no JavaScript thread involvement during the gesture — making it indistinguishable from a native implementation.
const composed = Gesture.Simultaneous(
Gesture.Exclusive(
doubleTap,
singleTap
),
pan,
pinch,
rotationGesture
);
const style = useAnimatedStyle(() => ({
transform: [
{ translateX: offsetX.value },
{ translateY: offsetY.value },
{ scale: scale.value },
{ rotate: rotation.value + 'rad' },
],
}));Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: Gesture.Pinch() provides event.scale to track two-finger zoom relative to the gesture start, Gesture.Rotation() provides event.rotation in radians to track two-finger twist, and Gesture.Simultaneous composes pinch, rotation, and pan so all three work at once for a full photo viewer experience. Next up we configure custom URL schemes for deep linking into specific app screens.
เรียนรู้ JavaScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 30
- บทเรียน
- 120
คำถามที่พบบ่อย
บทเรียน “การซูมด้วยการบีบนิ้วและการหมุน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การซูมด้วยการบีบนิ้วและการหมุน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การซูมด้วยการบีบนิ้วและการหมุน”
ใช้ PinchGestureHandler และ RotationGestureHandler ร่วมกับการตรวจจับท่าทางพร้อมกัน เพื่อสร้างคอมโพเนนต์รูปภาพที่ซูมและหมุนได้ คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “การซูมด้วยการบีบนิ้วและการหมุน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม
ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การติดตั้ง Reanimated และค่าที่ใช้ร่วมกัน
- เวิร์กเล็ตและการรันโค้ดบนเธรด UI
- ท่าลากและปัดด้วย Gesture Handler
- การซูมด้วยการบีบนิ้วและการหมุน