AspectRatio Component
Installation
The AspectRatio component helps maintain consistent proportions for content across different screen sizes.
Installation Command
npx @nativecn/cli add aspectratio
Basic Usage
Basic AspectRatio
Common Ratios
Different Aspect Ratios
With Custom Content
Map Preview
Usage Examples
Image Gallery Item
import { AspectRatio } from '@nativecn/ui';
import { Image, View, Text, StyleSheet } from 'react-native';
export function GalleryItem({ imageUrl, title }) {
return (
<View style={styles.container}>
<AspectRatio ratio={4/3}>
<Image
source={{ uri: imageUrl }}
style={styles.image}
/>
</AspectRatio>
<Text style={styles.title}>{title}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
borderRadius: 8,
overflow: 'hidden',
backgroundColor: '#fff',
},
image: {
width: '100%',
height: '100%',
},
title: {
padding: 12,
fontSize: 16,
fontWeight: '500',
},
});
Video Thumbnail
import { AspectRatio } from '@nativecn/ui';
import { View, Image, TouchableOpacity, StyleSheet } from 'react-native';
import Icon from 'react-native-vector-icons/Feather';
export function VideoThumbnail({ thumbnailUrl, onPress }) {
return (
<TouchableOpacity onPress={onPress}>
<AspectRatio ratio={16/9}>
<Image
source={{ uri: thumbnailUrl }}
style={styles.thumbnail}
/>
<View style={styles.overlay}>
<Icon name="play-circle" size={48} color="#fff" />
</View>
</AspectRatio>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
thumbnail: {
width: '100%',
height: '100%',
},
overlay: {
...StyleSheet.absoluteFillObject,
backgroundColor: 'rgba(0,0,0,0.3)',
justifyContent: 'center',
alignItems: 'center',
},
});
Reference
AspectRatio Props
interface AspectRatioProps {
// The desired aspect ratio (width/height)
ratio?: number;
// Optional className for styling
className?: string;
// Content to maintain the aspect ratio
children: React.ReactNode;
}