Site icon May's Notes

React Native Image Gallery

React Native logo

最近在嘗試手寫 Image Gallery,最開始是用 GestureDetector + Animated 寫的,雖然可以實現組件最基本的效果但滑動切換圖片還是不夠絲滑,會有卡頓的感覺。

在網上找了很多資料也沒看到比較好的做法,結果在翻看 ScrollView 的源碼時看到了 pagingEnabled 這個屬性,可用於水平翻頁。而 FlatList 繼承了 ScrollView 的屬性,所以想著乾脆用 FlatList + pagingEnabled 實現 Image Gallery 試試,一試才發現效果比我花了一堆時間在手寫動畫效果還好。

import React from 'react'
import {
  StyleSheet,
  Dimensions,
  FlatList,
  NativeSyntheticEvent,
  NativeScrollEvent,
} from 'react-native'

// ...

const ImageGallery = ({ images, currentIndex, imageSize }: ImageGalleryProps) => {
  // ...
  const renderItem = ({ uri }: { uri: string }) => (
    <Image
      source={{ uri }}
      style={{
        width: imageSize.width,
        height: imageSize.height,
      }}
      contentFit="contain"
      cachePolicy="memory-disk"
    />
  )

  return (
    <FlatList
      data={images}
      keyExtractor={(item) => item}
      horizontal={true}
      pagingEnabled={true}
      showsHorizontalScrollIndicator={false}
      initialScrollIndex={currentIndex}
      contentContainerStyle={styles.images}
      getItemLayout={(_, index) => ({
        length: width,
        offset: width * index,
        index,
      })}
      renderItem={renderItem}
    />
  )
}

export default ImageGallery

Exit mobile version