Write the App Code
Open App.tsx and replace its contents with the following code:
import React, { useRef, useState } from 'react';
import { StyleSheet, View, Text, ImageBackground, TouchableOpacity, Platform, Alert } from 'react-native';
import ViewShot, { captureRef } from 'react-native-view-shot';
import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';
const App: React.FC = () => {
const viewRef = useRef<any>();
const [quote, setQuote] = useState<string>(
'Believe you can and you\'re halfway there.'
);
const handleCaptureAndSave = async () => {
try {
// Capture the view as an image
const uri = await captureRef(viewRef, {
format: 'png',
quality: 1,
});
// Save the image to the device's file system
const fileName = `wallpaper-${Date.now()}.png`;
const fileUri = FileSystem.cacheDirectory + fileName;
await FileSystem.moveAsync({
from: uri,
to: fileUri,
});
// Share the image or guide the user to set it as wallpaper
if (Platform.OS === 'ios') {
await Sharing.shareAsync(fileUri);
} else if (Platform.OS === 'android') {
await Sharing.shareAsync(fileUri);
}
Alert.alert('Success', 'Image saved! You can now set it as your wallpaper.');
} catch (error) {
console.error(error);
Alert.alert('Error', 'Failed to save the image.');
}
};
return (
<View style={styles.container}>
<ViewShot ref={viewRef} options={{ format: 'png', quality: 1 }}>
<ImageBackground
source={require('./assets/background.jpg')}
style={styles.backgroundImage}
>
<View style={styles.overlay}>
<Text style={styles.quoteText}>{quote}</Text>
</View>
</ImageBackground>
</ViewShot>
<TouchableOpacity style={styles.button} onPress={handleCaptureAndSave}>
<Text style={styles.buttonText}>Save Image</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 50,
alignItems: 'center',
backgroundColor: '#fff',
},
backgroundImage: {
width: 300,
height: 500,
justifyContent: 'center',
alignItems: 'center',
},
overlay: {
backgroundColor: 'rgba(0, 0, 0, 0.5)',
padding: 20,
},
quoteText: {
color: 'white',
fontSize: 24,
textAlign: 'center',
},
button: {
marginTop: 20,
backgroundColor: '#1e90ff',
paddingVertical: 10,
paddingHorizontal: 20,
borderRadius: 5,
},
buttonText: {
color: '#fff',
fontSize: 18,
},
});
export default App;