Bỏ qua để đến nội dung

Hiệu ứng media

Demo chạy thật. Vuốt, chạm thử.Mở toàn màn hình ↗

Mọi preset, một hiệu ứng tự viết và các thông số liquid, chỉnh trực tiếp.

Một hiệu ứng media nhận khoảng cách có dấu từ trang của ảnh tới vị trí hiện tại (offset: 0 là đang hiển thị, -1 là lùi một trang, 0.5 là nửa đường tới trang sau) và trả về opacity, transform. Nó chạy trên UI thread nên phải là worklet:

import type { MediaEffectFn } from 'expo-morph-carousel';
const flip: MediaEffectFn = ({ offset }) => {
'worklet';
const angle = Math.max(-1, Math.min(1, offset)) * 90;
return {
opacity: Math.abs(offset) < 0.5 ? 1 : 0,
transform: [{ perspective: 800 }, { rotateY: `${angle}deg` }],
};
};
<MorphCarousel effect={flip} … />

Đầu vào còn có width, height, direction và rtl. Các preset có sẵn được export dưới tên mediaEffects nếu bạn muốn bọc lại một preset.

Mọi ảnh gần trang hiện tại được xếp chồng trong một layer Skia và cross-fade theo khoảng cách trang. Sau đó layer đi qua hai bộ lọc:

  1. Blur, với bán kính đạt đỉnh ở giữa hai trang. Hai ảnh tan vào nhau thành một hình mềm.
  2. Alpha threshold, tức một color matrix trên kênh alpha, cắt viền mờ về lại một đường viền sắc. Hình mềm trở thành một khối đặc thay vì một đám mờ.

Cả hai bộ lọc tỉ lệ theo một đường tam giác: bằng 0 khi ở đúng trang và bằng 1 ở giữa hai trang, nên trang đứng yên được vẽ nguyên vẹn.

Với ảnh chụp (mediaFit="cover"), bước cắt alpha còn làm bo tròn góc và ăn vào mép khung chữ nhật trong lúc chuyển. liquid={{ preserveShape: true }} giữ nguyên khung: blur chỉ nằm trong vùng ảnh và lặp lại điểm ảnh ở mép, không có bước cắt alpha, nên góc vẫn vuông và chỉ phần nội dung tan vào nhau.

Khi nào ảnh được giải mã. Giải mã một ảnh chặn thread chạy nó (JPEG 1080×810 mất vài chục mili giây). Skia giải mã lười ở lần vẽ đầu tiên, tức là trên UI thread, đúng lúc cú vuốt đưa trang đó vào. liquid.decode chuyển việc đó đi:

  • 'scheduled' (mặc định): trên JS thread khi trang được mount trước, mỗi task một ảnh, trang đang xem trước. Ảnh của trang đã ra khỏi cửa sổ trước lượt của nó thì bỏ qua.
  • 'immediate': trên JS thread ngay khi đọc xong file.
  • 'onDraw': mặc định của Skia, trên UI thread ở lần vẽ đầu.

Đo trên Redmi Note 8 Pro (Helio G90T, Expo Go, JS production) bằng màn Stress test của example, 40 trang cách nhau 350 ms: 'onDraw' rớt khoảng một khung hình mỗi trang (40–41 khung trên 25 ms, dài nhất 133 ms). 'immediate' và 'scheduled' rớt 0–1, khung dài nhất 17 ms. Bù lại JS thread bận hơn: khoảng 15 lần trên 100 ms trong 40 trang, còn onIndexChange vẫn chạy trung bình 9 ms sau khi đổi trang. 'scheduled' và 'immediate' đo như nhau; hàng đợi chỉ chặn trên các trường hợp nhiều ảnh tới cùng lúc.

Các trang chữ là view React Native thông thường và trượt; chỉ vùng media được vẽ bằng Skia.

example/app/playground.tsx
import { MorphCarousel, type MediaEffect, type MediaEffectFn } from 'expo-morph-carousel';
import { useState } from 'react';
import { Pressable, ScrollView, StyleSheet, Switch, Text, View } from 'react-native';
import { products } from '../data/products';
import { column } from '../data/layout';
/** A custom effect: the image turns like a card around its vertical axis. */
const flip: MediaEffectFn = ({ offset }) => {
'worklet';
const angle = Math.max(-1, Math.min(1, offset)) * 90;
return {
opacity: Math.abs(offset) < 0.5 ? 1 : 0,
transform: [{ perspective: 800 }, { rotateY: `${angle}deg` }],
};
};
const effects: { label: string; value: MediaEffect }[] = [
{ label: 'liquid', value: 'liquid' },
{ label: 'crossfade', value: 'crossfade' },
{ label: 'slide', value: 'slide' },
{ label: 'parallax', value: 'parallax' },
{ label: 'stack', value: 'stack' },
{ label: 'custom flip', value: flip },
];
export default function PlaygroundScreen() {
const [effect, setEffect] = useState(0);
const [loop, setLoop] = useState(true);
const [autoplay, setAutoplay] = useState(false);
const [vertical, setVertical] = useState(false);
const [blur, setBlur] = useState(28);
const [index, setIndex] = useState(0);
return (
<ScrollView contentInsetAdjustmentBehavior="automatic" contentContainerStyle={[styles.screen, column]}>
<MorphCarousel
// Remount when the direction changes: the pages are laid out per axis.
key={vertical ? 'v' : 'h'}
testID="playground-carousel"
data={products}
keyExtractor={(p) => p.id}
getImage={(p) => p.image}
getPlaceholderColor={(p) => p.color}
getAccessibilityLabel={(p) => p.title}
effect={effects[effect].value}
liquid={{ blur }}
loop={loop}
autoplay={autoplay ? { interval: 2500 } : false}
direction={vertical ? 'vertical' : 'horizontal'}
initialIndex={index}
onIndexChange={setIndex}
mediaHeight={240}
mediaPadding={24}
style={styles.card}
renderItem={({ item }) => (
<View style={styles.page}>
<Text style={styles.title}>{item.title}</Text>
</View>
)}
/>
<Text style={styles.label}>Effect</Text>
<View style={styles.chips}>
{effects.map((e, i) => (
<Pressable
key={e.label}
onPress={() => setEffect(i)}
style={[styles.chip, i === effect && styles.chipOn]}
testID={`effect-${e.label}`}
>
<Text style={[styles.chipText, i === effect && styles.chipTextOn]}>{e.label}</Text>
</Pressable>
))}
</View>
{effects[effect].value === 'liquid' && (
<>
<Text style={styles.label}>Liquid blur: {blur}</Text>
<View style={styles.chips}>
{[12, 20, 28, 40, 56].map((b) => (
<Pressable
key={b}
onPress={() => setBlur(b)}
style={[styles.chip, b === blur && styles.chipOn]}
>
<Text style={[styles.chipText, b === blur && styles.chipTextOn]}>{b}</Text>
</Pressable>
))}
</View>
</>
)}
<View style={styles.toggles}>
<Toggle label="Loop" value={loop} onChange={setLoop} />
<Toggle label="Autoplay (2.5 s)" value={autoplay} onChange={setAutoplay} />
<Toggle label="Vertical" value={vertical} onChange={setVertical} />
</View>
</ScrollView>
);
}
function Toggle({
label,
value,
onChange,
}: {
label: string;
value: boolean;
onChange: (v: boolean) => void;
}) {
return (
<View style={styles.toggle}>
<Text style={styles.toggleText}>{label}</Text>
<Switch value={value} onValueChange={onChange} accessibilityLabel={label} />
</View>
);
}
const styles = StyleSheet.create({
screen: { padding: 16, gap: 10 },
card: { height: 360, borderRadius: 24, backgroundColor: '#fff' },
page: { flex: 1, alignItems: 'center', justifyContent: 'center' },
title: { fontSize: 22, fontWeight: '700', color: '#1c1c1e' },
label: { marginTop: 8, fontSize: 13, color: '#6e6e73' },
chips: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
chip: { paddingHorizontal: 12, paddingVertical: 8, borderRadius: 999, backgroundColor: '#fff' },
chipOn: { backgroundColor: '#5b4bd6' },
chipText: { fontSize: 14, color: '#1c1c1e' },
chipTextOn: { color: '#fff', fontWeight: '600' },
toggles: { marginTop: 8, borderRadius: 16, backgroundColor: '#fff', paddingHorizontal: 14 },
toggle: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingVertical: 10,
},
toggleText: { fontSize: 15, color: '#1c1c1e' },
});