React Native 图像大小调整不会导致宽度改变

编程入门 行业动态 更新时间:2024-10-12 22:28:12
本文介绍了React Native 图像大小调整不会导致宽度改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在 React Native 0.53.0 中制作位置图标.我创建了一个位置标记的 png,其大小为 114 x 200.然后,我创建了一个组件,它具有以下渲染方法:

I'm trying to make an location icon in react native 0.53.0. I created a png of a location marker, which has a size of 114 x 200. Then, I created a component, which has the following render method:

render() { return ( <Image source={locationImg} resizeMode="contain" style={{ flex: 1 }} /> ); }

然后我在高度为 50px 和填充为 5px 的视图中使用这个组件,这意味着图标的高度为 40px.然后我会假设我的图标组件的宽度约为 23px,但事实并非如此.尽管使用了 resizeMode="contain",宽度并没有缩小,而是保持在图像的原始尺寸 114px.

I then use this component in a View that has a height of 50px and a padding of 5px, meaning the icon will have a height of 40px. I would then assume that the width of my icon component would be about 23px, but this is not the case. Despite the resizeMode="contain", the width does not get scaled down, but stays at the original size of the image, 114px.

为什么宽度没有缩小,我应该怎么做才能达到我想要的结果?

Why doesn't the width scale down as well, and what should I do differently to achieve my wanted result?

推荐答案

我想出了以下组件:

import React, { Component } from 'react'; import { Image, View } from 'react-native'; import locationImg from '../assets/images/locationImage.png' // Calculate the ratio to be able to scale the width correctly const { width: WIDTH, height: HEIGHT } = Image.resolveAssetSource(locationImg); const RATIO = WIDTH / HEIGHT; class LocationIcon extends Component { // Have the desired width of the component in state state = { width: 0 }; // When receiveing layout, calculate the desired width and update state onLayout = event => { const { height } = event.nativeEvent.layout; this.setState({ width: height * RATIO }); } render() { return ( <View> <Image source={locationImg} resizeMode="contain" onLayout={this.onLayout} style={{ flex: 1, width: this.state.width, // Update width from state }} /> </View> ); } } export default LocationIcon;

更多推荐

React Native 图像大小调整不会导致宽度改变

本文发布于:2023-10-11 14:26:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1481966.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:宽度   图像   大小   React   Native

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!