constructor(props) {
super(props);
this.state = {
screenWidth: Dimensions.get('window').width,
heightScaled: null,
};
}
<View style={styles.videoView}>
<Video
source={video}
ref={(ref) => { this.player = ref }}
repeat={true}
resizeMode={"contain"}
style={{
width: this.state.screenWidth,
height: this.state.heightScaled,
}}
onLoad={response => {
const { width, height } = response.naturalSize;
const heightScaled = height * (this.state.screenWidth / width);
response.naturalSize.orientation = "horizontal";
this.setState({ heightScaled: heightScaled });
}}
/>
</View>
styles
videoView: {
flex: 1,
width: Dimensions.get('window').width,
height: 350
}
I'm fetching video from api and then using it in a video component using react-native-video. I don't know how I can resize my video to fit in a view without stretching the video.
Here is the result of the above code.
I don't want my video to cross the red line I marked in the image.
Please help me. I'm stuck on this problem from the past 3 days.
Adding one more <View /> inside the parent <View /> containing <Video /> will solve the overflow of the video.
<View style={styles.videoView}>
<Video
resizeMode={"contain"}
style={{
flex: 1
}}
/>
<View style={{flex: 1}}>
{/* Components after red line can be rendered here */}
</View>
</View>
Related
I am new to react-native (started 2 days ago) but I picked it up quickly because I already knew regular react. I'm trying to write a real world app and I can't figure out how to place an image correctly, I want my Image tag to take up all horizontal space on the screen, but I also want it to stay at the very top of the screen and keep its aspect ratio (which I can't hardcode because I will also display other pictures of licence plates, including european ones that are not 2/1 like in north america), all while not having the actual image take up all available vertical space.
Here is a GIMP edit of what my code renders and what I actually want:
https://ibb.co/XJgrhkC
Here is my render function:
export default class App extends Component {
...
render() {
return (
<View style={{ flex: 1, justifyContent: 'flex-start', alignItems: 'center' }}>
<Image
source={require(`./resources/images/north_america/original/alaska.jpg`)}
style={{ flex: 1, width: screenWidth }}
resizeMode="contain" />
<Button title="Random state" onPress={this.getRandomState} />
</View>
);
}
}
I am familiar with css's layout options but react-native seems to be different and I can't wrap my head around all the combinations of widths, flex and resizeModes.
typically, upon applying flex to the <View /> tag enclosing the <Image /> and the <Button />, the children of the parent component will have the same flex prop applied. so, you can remove the flex prop under <Image />.
having dealt with <Image /> in react-native for some time, i must say that specifying values for both height and width is important for an <Image /> to be displayed properly.
you can try it out on my Expo example here.
render() {
return (
<View style={{
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center'
}}>
<Image
source={require(`./resources/images/north_america/original/alaska.jpg`)}
style={{
width: screenWidth,
height: 200,
}}
resizeMode="contain"
/>
<Button
title="Random state"
onPress={this.getRandomState}
/>
</View>
);
}
also, since you are new to react-native, may i suggest you change <Button /> to <TouchableOpacity />? it provides a visual aid when user presses it on a mobile device.
When you use flex, you can see the image automatically occupying a lot of space when you add {borderWidth: 2, borderColor: 'red'}. Instead, you have to specify the height manually. If you want it to be scaled properly, you can try this:
import React from "react";
import { View, Image, Button, Dimensions } from "react-native";
class App extends React.Component {
state = {
imgWidth: 0,
imgHeight: 0
};
componentDidMount() {
Image.getSize("https://i.ibb.co/HgsfWpH/sc128.jpg", (width, height) => {
// Calculate image width and height
const screenWidth = Dimensions.get("window").width;
const scaleFactor = width / screenWidth;
const imageHeight = height / scaleFactor;
this.setState({ imgWidth: screenWidth, imgHeight: imageHeight });
});
}
render() {
return (
<View
style={{ flex: 1, justifyContent: "flex-start", alignItems: "center" }}
>
<Image
style={{
flex: 1,
width: Dimensions.get("window").width,
borderColor: "red",
borderWidth: 2
}}
source={{
uri: "https://i.ibb.co/HgsfWpH/sc128.jpg"
}}
resizeMode="contain"
/>
<Button title="Random state" onPress={this.getRandomState} />
</View>
);
}
}
export default App;
I am using <Image> and <ImageBackground> with source:{{ uri: url }} inside my React Native project.
But the problem is an image is not showing inside Android simulator (But IOS simulator is fine)
This is my component
import React from 'react'
import {
Text, StyleSheet, ImageBackground, Image,
} from 'react-native'
import { Header } from 'react-navigation'
import { dimens } from '../../../services/variables'
const CustomHeader = ({ bgSrc }) => (
<ImageBackground
source={
bgSrc
? { uri: bgSrc }
: require('../../../assets/images/placeholder_image_bg_wide.png')
}
style={styles.header}
>
<Text style={styles.description}>First element</Text>
<Image source={{ uri: 'https://i.vimeocdn.com/portrait/58832_300x300.jpg' }} style={{ width: 200, height: 45, backgroundColor: 'red' }} />
<Text style={styles.description}>Second element</Text>
<Image source={{ uri: 'http://i.vimeocdn.com/portrait/58832_300x300.jpg' }} style={{ width: 200, height: 45 }} />
<Text style={styles.title}>Last element 1</Text>
</ImageBackground>
)
export default CustomHeader
const styles = StyleSheet.create({
header: {
minHeight: Header.HEIGHT,
height: dimens.header.height,
marginTop: dimens.header.marginTop,
paddingLeft: dimens.header.paddingLeft,
paddingBottom: dimens.header.paddingBottom,
backgroundColor: 'blue',
flexDirection: 'column-reverse',
},
title: {
...dimens.header.title,
},
description: {
...dimens.header.description,
},
})
I also already added permissions inside AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
This is the image of my both simulators
You will see that on IOS simulator <Image> is showing correctly but not on Android none images were show (Both http and https)
So how can i fix these and make Android simulator works, Thanks!
I have said this before in another question
https://stackoverflow.com/a/71263771/8826164
but there is an issue with Image component is that if first time initialize the component with source={{uri : 'some link'}} it may not work (at least not for me when I fetch image from HTTPS URL from Firebase storage). The trick is you have to trigger a change to source props like first you need to keep
source to source={undefined} and then change to source={{uri : 'some link'}}. And it seems like you have hard-coded URL for uri, so you might fall into the same issue as I did
Before :
<Image source={{ url: http://stitch2stitch.azurewebsites.net/assets/img/FileFormats/${result}.png}} style={{ height: 40, width: 40, }} />
After :
<Image source={{uri: http://stitch2stitch.azurewebsites.net/assets/img/FileFormats/${result}.png}} style={{ height: 40, width: 40, }} />
just change from url to uri works for me
I am trying to design this design react-native. This is what I have coded for this but this is not what I want. This works on one screen only, if I change screen size then things are not working.
This looks like absolute layout. What changes should I make to make it in such a way so that it will work on all screen sizes.
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from "react";
import {
AppRegistry,
Image,
View,
Text,
Button,
StyleSheet
} from "react-native";
class SplashScreen extends Component {
render() {
console.disableYellowBox = true;
return (
<View style={styles.container}>
<Image
source={require("./img/talk_people.png")}
style={{ width: 300, height: 300 }}
/>
<Text style={{ fontSize: 22, textAlign: "center", marginTop: 30 }}>
Never forget to stay in touch with the people that matter to you.
</Text>
<View style={{ marginTop: 60, width: 240 }}>
<Button title="CONTINUE" color="#FE434C" />
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#FFFFFF",
margin: 50,
alignItems: "center",
flex: 1,
flexDirection: "column"
}
});
AppRegistry.registerComponent("Scheduled", () => SplashScreen);
Expected State:
Current State:
Nexus 4 - 768x1280
Nexus 6P - 1440x2560
The quick answer is to use flex within your outer container, such that you have, say:
<View style={{flex: 1}}>
<View style={{flex: 2}}>
<.../>//Image
</View>
<View style={{flex: 1}}>
<.../>//Text
</View>
<View style={{flex: 1}}>
<.../>//Button
</View>
</View>
which will divide the container into quarters and give the top half of the screen to the image and the other two quarters to the text and button; you can use padding and margins with these as you like, and use any ratio you want.
What further needs to be considered, though, is screen pixel density, which can really wreak havoc with display sizes. I've found it handy to have an outside
import React from 'react';
import { PixelRatio } from 'react-native';
let pixelRatio = PixelRatio.get();
export const normalize = (size) => {
switch (true){
case (pixelRatio < 1.4):
return size * 0.8;
break;
case (pixelRatio < 2.4):
return size * 1.15;
break;
case (pixelRatio < 3.4):
return size * 1.35;
break;
default:
return size * 1.5;
}
}
export const normalizeFont = (size) => {
if (pixelRatio < 1.4){
return Math.sqrt((height*height)+(width*width))*(size/175);
}
return Math.sqrt((height*height)+(width*width))*(size/100);
}
module which I use as
import { normalize, normalizeFont } from '../config/pixelRatio';
const {width, height} = require('Dimensions').get('window');
...and for an image, say:
<Image source={ require('../images/my_image.png') } style={ { width: normalize(height*.2), height: normalize(height*.2) } } />
and a font:
button_text: {
fontSize: normalizeFont(configs.LETTER_SIZE * .7),
color: '#ffffff'
},
Hope this helps!
Edit: The module above has worked for me for devices I've deployed to, but it should be expanded to allow for pixelRatio values of from 1 to 4 with some decimal (e.g. 1.5) values in there, too. There's a good chart at this link that I'm working from to try to finish this out, but so far what has worked best is as I've posted above.
Another great way of creating dynamic layout is by using the Dimensions, Personally I hate flex (couldn't understand it at times) Using Dimensions You could get the screen width and height. After which you could divide the result and assign them to top level components
import React, { Component } from "react";
import {
View,
StyleSheet,
Dimensions
} from "react-native";
const styles = StyleSheet.create({
container: {
backgroundColor: "#FFFFFF",
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
//height:Dimensions.get('window').height*0.5// 50% of the screen
margin: 50,
alignItems: "center",
flex: 1,
flexDirection: "column"
}
});
Also adding to this, came across this library that supports media queries, if you are comfy with css styles just give it a try
My js is abit rusty and im abit confused about how to update the state after a swipe event in my react-native android app. Im trying to hookup this ViewPager based on the official ViewPager and i just want to get the pagenum to update when the slider slides to that page. Any help on how?
The slider itself works, but im confused about how to update state based on events or callbacks. What i really wish to do is update the background color styling of the parent view after each page slide.
Welcome Page
import {IndicatorViewPager, PagerDotIndicator} from 'rn-viewpager';
var AboutPage1 = require('../about/AboutPage1');
var AboutPage2 = require('../about/AboutPage2');
class WelcomeScreen extends Component {
state = {
pagenum: 0
};
render() {
<View >
// the parent view i wish to change bgcolor
<View style={{flex:1}}>
// this is the viewpager
<IndicatorViewPager
indicator={this._renderDotIndicator()}
onPageScroll={this.onPageScroll}
onPageSelected={this.onPageSelected}
onPageScrollStateChanged={this.onPageScrollStateChanged}
ref={viewPager => { this.viewPager = viewPager;
}}>
// some components in this first view
<View onPress={this.onPageSelected.bind(this,this.pagenum)}>
// some components
</View>
// these are just views wrapping pages that are themselves views
<View onPress={this.onPageSelected.bind(this,this.pagenum)}>
<AboutPage1 onPress={this.onPageSelected.bind(this, this.pagenum)}/>
<Text>{'count' + this.state.pagenum}</Text>
</View>
<View>
<AboutPage2 onPress={this.onPageSelected.bind(this, this.pagenum)}/>
<Text>{'count' + this.state.pagenum}</Text>
</View>
</IndicatorViewPager>
</View>
</View>
);
}
_renderDotIndicator() {
return (
<PagerDotIndicator
pageCount={5}
/>
);
}
// callback that is called when viewpager page is finished selection
onPageSelected(e) {
console.log('state is: '+this.state)
this.SetState({pagenum: this.state.pagenum+1});
console.log('state is: '+this.state)
}
}
About Page
<View>
<Text>Welcome to My App</Text>
</View>
Error
error: 'undefined is not an object when evaluating this.state.pagecount
You should bind this keyword.Like this:
<IndicatorViewPager
indicator={this._renderDotIndicator()}
onPageScroll={this.onPageScroll.bind(this)}
onPageSelected={this.onPageSelected.bind(this)}
onPageScrollStateChanged={this.onPageScrollStateChanged.bind(this)}
ref={viewPager => { this.viewPager = viewPager;
}}>
...
</IndicatorViewPager>
You might be mixing up two different plugins but using ViewPager from '#react-native-community/viewpager', What you want to achieve can be done as follows (Notice the use of onPageSelected and the handler);
<ViewPager
pageMargin={10}
style={styles.viewPager}
initialPage={currentPageIndex}
onPageSelected={(eventDate) => this.handleHorizontalScroll(eventDate.nativeEvent)}
>
{pages.map((item) => (
<Card style={{ elevation: 3, margin: 50, borderRadius: 10, backgroundColor }}>
<CardItem header style={{ borderRadius: 10, backgroundColor }} bordered>
<Text>Card Header</Text>
</CardItem>
<CardItem style={{ flex: 1, borderBottomWidth: 0.2, backgroundColor }}>
<ScrollView>
<Text style={{ fontFamily, color, fontSize, textAlign: 'justify' }}>
{item.text}
</Text>
</ScrollView>
</CardItem>
<CardItem style={{ borderRadius: 10, backgroundColor }}>
<Text>Card Footer</Text>
</CardItem>
</Card>
))}
</ViewPager>
Your horizontal Scroll handler or onPageSelectedHandler should then be something like this:
handleHorizontalScroll = ({ position }) => {
console.log('Current Card Index', position);
this.setState({currentIndex: position})
};
I want to make a screen with a full-width Android screen image, but however, for some reason I cannot do it. I have done every single solution available in SO but it still persists.
Here is my code:
<View style={styles.loginContainer}>
<Image
style={styles.background}
source={require('./image.png')}
//source={{uri: 'http://previews.123rf.com/images/background.jpg'}}
opacity={0.8}
>
<Login navigator={navigator} />
</Image>
</View>
and my Stylesheet:
var styles = StyleSheet.create({
loginContainer: {
alignSelf: 'stretch',
flex: 1,
alignItems: 'stretch'
},
background: {
alignSelf: 'stretch',
flex: 1,
alignItems: 'stretch'
},
});
For some reason it worked just fine when I used network images, but when I used static images, it will only cover 2/3 width but full height. I have also tried source={{uri: 'image.png', isStatic: true}}, but it gives me null error. Any solution is much appreciated. Thanks.
Yes, there is an open issue on Github.
First of all, I would suggest using the resizeMode property, for instance:
<Image
style={styles.background}
source={require('./image.png')}
opacity={0.8}
resizeMode="contain"
>
Then, for network images, this would work:
var styles = StyleSheet.create({
loginContainer: {
flex: 1,
},
background: {
flex: 1,
},
});
For 'required' images, it does not work, as you pointed out, so you can either specify the width yourself:
var width = require('Dimensions').get('window').width;
var styles = StyleSheet.create({
loginContainer: {
flex: 1,
},
background: {
flex: 1,
width: width,
},
});
Or even set it to null:
var styles = StyleSheet.create({
loginContainer: {
flex: 1,
},
background: {
flex: 1,
width: null,
},
});
You can use react-native-scalable-image. The following example will give you a full screen width image:
import React from 'react';
import { Dimensions } from 'react-native';
import Image from 'react-native-scalable-image';
const image = <Image width={Dimensions.get('window').width} source={{uri: '<image uri>'}} />;
try this android:scaleType="fitXY"
<ImageView
android:id="#+id/image_view_full"
android:layout_width="fill_parent"
android:scaleType="fitXY"
android:layout_height="fill_parent" />