我是react-native的新手。 我想要做的是将图像适合设备并保持图像的比例。只是我想做
width : 100%
我搜索了如何制作它,似乎
resizeMode = 'contain'
对此很有好处。
但是,由于我使用了
resizeMode = 'contain'
,图像保持位置垂直居中,这是我不想要的。
我希望它垂直顶部。
我尝试使用诸如 react-native-fit-image 之类的插件,但没有成功。
我发现了图像没有自动调整大小的原因。 但我还是不知道如何制作。
所以,我的问题是处理这种情况的最佳方法是什么?
我必须手动设置每个图像的
width, height
尺寸吗?
我想要:
React 本机测试代码:
https://snack.expo.io/ry3_W53rW
最终我想做的:
https://jsfiddle.net/hadeath03/mb43awLr/
谢谢。
图像垂直居中,因为您将
flex: 1
添加到了 style 属性。不要添加 flex: 1,因为这会将图像填充到其父级,这在本例中是不需要的。
您应该始终在 React Native 中添加图像的高度和宽度。如果图像始终相同,您可以使用
Dimensions.get('window').width
来计算图像应有的大小。例如,如果比例始终为 16x9,则高度为图像宽度的 9/16。宽度等于设备宽度,因此:
const dimensions = Dimensions.get('window');
const imageHeight = Math.round(dimensions.width * 9 / 16);
const imageWidth = dimensions.width;
return (
<Image
style={{ height: imageHeight, width: imageWidth }}
/>
);
注意:使用这样的实现时,旋转设备、使用分屏等时,您的图像不会自动调整大小。如果您支持多个方向,您还必须注意这些操作...
如果比例不同,请根据每个不同图像的比例动态更改 9 / 16。如果您真的不介意图像被裁剪了一点,您也可以使用固定高度的覆盖模式:(https://snack.expo.io/rk_NRnhHb)
<Image
resizeMode={'cover'}
style={{ width: '100%', height: 200 }}
source={{uri: temp}}
/>
也只是为了尝试一下
您还可以等待 Image onLayout 回调来获取其布局属性并使用它来更新尺寸。我为此创建了一个组件:
import * as React from 'react';
import { Dimensions, Image, ImageProperties, LayoutChangeEvent, StyleSheet, ViewStyle } from 'react-native';
export interface FullWidthImageState {
width: number;
height: number;
stretched: boolean;
}
export default class FullWidthImage extends React.Component<ImageProperties, FullWidthImageState> {
constructor(props: ImageProperties) {
super(props);
this.state = { width: 100, height: 100, stretched: false };
}
render() {
return <Image {...this.props} style={this.getStyle()} onLayout={this.resizeImage} />;
}
private resizeImage = (event: LayoutChangeEvent) => {
if (!this.state.stretched) {
const width = Dimensions.get('window').width;
const height = width * event.nativeEvent.layout.height / event.nativeEvent.layout.width;
this.setState({ width, height, stretched: true });
}
};
private getStyle = (): ViewStyle => {
const style = [StyleSheet.flatten(this.props.style)];
style.push({ width: this.state.width, height: this.state.height });
return StyleSheet.flatten(style);
};
}
这将更新图像的尺寸以匹配屏幕的宽度。
您可以将此样式应用于图像:如果将 Image 应用于图像标签,则图像宽度为完整图像。
const win = Dimensions.get('window');
export default function App() {
return (
<View style={styles.container}>
<Image
style={{
width: win.width/1,
height: win.width/5,
resizeMode: "contain",
alignSelf: "center",
borderRadius: 20,
}}
source={require('./assets/logo.png')}
/>
</View>
);
}
您可以将此样式应用于图像: 如果将
imageStyle
应用于 Image
标签,则图像宽度将为 100%,图像高度将为 300。
imageStyle:{
height:300,
flex:1,
width:null
}
假设您的图像代码是:
<Image style={imageStyle} source={{uri:'uri of the Image'}} />
右键单击您的图像以获得分辨率。就我而言,1233 x 882
const { width } = Dimensions.get('window');
const ratio = 882 / 1233;
const style = {
width,
height: width * ratio
}
<Image source={image} style={style} resizeMode="contain" />
这一切
我有一个组件,它采用图像道具并进行适当的调整(并在
ScrollView
和 require
d 资源中工作。在滚动视图中,它使用图像的高度作为高度,无论它是否按比例缩放导致一些多余的填充。该组件执行大小计算并重新调整图像样式以使用 100% 宽度,保留加载的文件的纵横比。
import React, { useState } from "react";
import { Image, ImageProps } from "react-native";
export function FullWidthImage(props: ImageProps) {
// Initially set the width to 100%
const [viewDimensions, setViewDimensions] = useState<{
width?: number | string;
height?: number | string;
}>({
width: "100%",
height: undefined,
});
const [imageDimensions, setImageDimensions] = useState<{
width?: number;
height?: number;
}>(() => {
if (typeof props.source === "number") {
// handle case where the source is an asset in which case onLoad won't get triggered
const { width, height } = Image.resolveAssetSource(props.source);
return { width, height };
} else {
return {
width: undefined,
height: undefined,
};
}
});
return (
<Image
onLayout={(e) => {
// this is triggered when the "view" layout is provided
if (imageDimensions.width && imageDimensions.height) {
setViewDimensions({
width: e.nativeEvent.layout.width,
height:
(e.nativeEvent.layout.width * imageDimensions.height) /
imageDimensions.width,
});
}
}}
onLoad={(e) => {
// this is triggered when the image is loaded and we have actual dimensions.
// But only if loading via URI
setImageDimensions({
width: e.nativeEvent.source.width,
height: e.nativeEvent.source.height,
});
}}
{...props}
style={[
props.style,
{
width: viewDimensions.width,
height: viewDimensions.height,
},
]}
/>
);
}
这是为了补偿
contain
,它会在图像周围添加额外的填充(这基本上使图像视图高度充满),即使图像宽度为 100%
。
请注意,您可能会尝试将其作为背景,在这种情况下,
ImageBackground
无法在 Android 上正确呈现。使用上面的代码进行一些调整,我创建了以下内容,可以使用长文本和短文本正确呈现内容。
import React, { PropsWithChildren } from "react";
import { ImageProps, View } from "react-native";
import { FullWidthImage } from "./FullWidthImage";
export function FullWidthImageBackground(props: PropsWithChildren<ImageProps>) {
const imageProps = { ...props };
delete imageProps.children;
return (
<View>
<FullWidthImage
{...imageProps}
style={{
position: "absolute",
}}
/>
{props.children}
</View>
);
}
注意,如果您将其与标题一起使用,则需要添加一个填充视图作为第一个子视图
<View
style={{
height: safeAreaInsets.top + (Platform.OS === "ios" ? 96 : 44),
}}
/>
const ImageHandler = ({ name, onPress }: any) => { const [ImgHeight, setImgHeight] = React.useState(width) return ( <TouchableOpacity activeOpacity={1} onPress={() => onPress()} style={{ width: width, height: ImgHeight, maxHeight:width, }} > <FastImage onLoad={(e) => { let newWidth = changeWidth ? changeWidth :width let hei = (e.nativeEvent.height/e.nativeEvent.width)*newWidth setImgHeight(hei) }} style={{ flex: 1, width: undefined, height: undefined, backgroundColor: colors.white, }} resizeMode={Platform.OS === "ios" ? "cover" : "cover"} source={{ uri: ${FILE_BASE_URL}${name} }} /> ); };