Ответ 1
React Native имеет встроенную функцию, которая будет возвращать ширину и высоту изображения: Image.getSize()
. Ознакомьтесь с документацией здесь
У меня есть изображение, которое я сбрасываю с URL-адреса. Я не знаю размеров этого изображения раньше времени.
Как стиль/макет <Image/>
, так что это полная ширина родительского представления, а высота вычисляется так, чтобы поддерживалось соотношение сторон?
Я попытался использовать onLoad
в 0.34.0-rc.0, а высота/ширина равны 0 в event.nativeEvent.source
.
Изображение находится в <ScrollView/>
. Я не после полноэкранного изображения.
React Native имеет встроенную функцию, которая будет возвращать ширину и высоту изображения: Image.getSize()
. Ознакомьтесь с документацией здесь
Мое использование было очень похоже на то, что мне нужно было отображать изображение с полноэкранной шириной, но поддерживало его соотношение сторон.
Основываясь на ответе @JasonGaare на использование Image.getSize()
, я придумал следующую реализацию:
class PostItem extends React.Component {
state = {
imgWidth: 0,
imgHeight: 0,
}
componentDidMount() {
Image.getSize(this.props.imageUrl, (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() {
const {imgWidth, imgHeight} = this.state
return (
<View>
<Image
style={{width: imgWidth, height: imgHeight}}
source={{uri: this.props.imageUrl}}
/>
<Text style={styles.title}>
{this.props.description}
</Text>
</View>
)
}
}
Я новичок в реакции-нативной, но я столкнулся с этим решением, используя простой стиль:
imageStyle: {
height: 300,
flex: 1,
width: null}
Изображение на всю ширину из моего приложения 1º
Это сработало для меня - что вы думаете?
Заранее спасибо.
Это сработало для меня.
import React from 'react'
import { View, Text, Image } from 'react-native'
class Test extends React.Component {
render() {
return (
<View>
<Image
source={{ uri: "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQL6goeE1IdiDqIUXUzhzeijVV90TDQpigOkiJGhzaJRbdecSEf" }}
style={{ height: 200, left: 0, right: 0 }}
resizeMode="contain"
/>
<Text style={{ textAlign: "center" }}>Papaya</Text>
</View>
);
}
}
export default Test;
Другой способ получить ширину родительского представления после события макета.
<View
style={{ flex: 1}}
layout={(event) => { this.setState({ width: event.nativeEvent.layout.width }); }}
/>
Когда вы получаете представление родительского представления ширины из события макета, вы можете назначить ширину тегу изображения.
import React from 'react';
import { View, Image } from 'react-native';
class Card extends React.Component {
constructor(props) {
super(props);
this.state = {
height: 300,
width: 0
};
}
render() {
return (
<View style={{
flex: 1,
flexDirection: 'row'
}}>
<View style={{ width: 50, backgroundColor: '#f00' }} />
<View
style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fafafa' }}
onLayout={(event) => { this.setState({ width: event.nativeEvent.layout.width }); }}
>
{
this.state.width === 0 ? null : (
<Image
source={{ uri: "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQL6goeE1IdiDqIUXUzhzeijVV90TDQpigOkiJGhzaJRbdecSEf" }}
style={{ width: this.state.width, height: this.state.height }}
resizeMode="contain"
/>
)
}
</View>
</View>
);
}
}
export default Card;
если у вас есть статичное изображение, вы можете использовать это
import React, { Component } from "react";
import { View, Animated, Image, Dimensions } from "react-native";
import splashScreen from "../../../assets/imgs/splash-screen.png";
export default class MasterPage extends Component {
constructor(props) {
super(props);
this.state = {
fadeAnim: new Animated.Value(0),
imgWidth: 0,
imgHeight: 0
};
}
checkLogIn = async () => {
const width = 533; // set your local image with
const height = 527; // set your local image 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 });
};
async componentDidMount() {
Animated.timing(
// Animate over time
this.state.fadeAnim, // The animated value to drive
{
toValue: 1, // Animate to opacity: 1 (opaque)
duration: 800, // Make it take a while
useNativeDriver: true
}
).start(this.checkLogIn);
}
render() {
const { imgWidth, imgHeight, fadeAnim } = this.state;
return (
<Animated.View
style={{
opacity: fadeAnim,
backgroundColor: "#ebebeb",
flex: 1,
justifyContent: "center",
alignItems: "center"
}}
>
<View>
<Image
source={splashScreen}
style={{ width: imgWidth, height: imgHeight }}
/>
</View>
</Animated.View>
);
}
}
incase, вы еще не можете его решить, React Native v.0.42.0 имеет resizeMode
<Image style={styles.intro_img} source={require('img.png')}