react-native icon indicating copy to clipboard operation
react-native copied to clipboard

Full width image using flexbox?

Open joshbedo opened this issue 11 years ago • 33 comments

I'm attempting to make an image full-width and came across a few stackoverflow questions related where the top upvoted answer was to use flexbox similarly to how i'm using it below. Although it doesn't seem to display the image unless i set static widths on my styles property. Any ideas?

var styles = StyleSheet.create({
  canvasContainer: {
    flex:1,
    alignItems: 'stretch'
  },
  canvas: {
    flex:1
   // width: 200,
   // height: 200
  }
});
render: function() {
    return (
      <View style={styles.container}>
        <View style={styles.canvasContainer}>
          <Image
            source={{uri: 'http://imgs.steps.dragoart.com/how-to-draw-a-pony-step-7_1_000000053055_5.jpg'}}
            style={styles.canvas} />
        </View>
        <ScrollView
          style={styles.scrollView}
          scrollEventThrottle={200}
          contentInset={{top: 0}}
          >
          {this.state.messages.map(m => {
            return <Text style={styles.message}>Josh: {m}</Text>
          })}
        </ScrollView>
      </View>
    )
  }

joshbedo avatar Apr 21 '15 15:04 joshbedo

canvas: {
  position: 'absolute',
  top: 0,
  left: 0,
  bottom: 0,
  right: 0,
},
<Image
  resizeMode="contain"
  source={{uri: 'http://imgs.steps.dragoart.com/how-to-draw-a-pony-step-7_1_000000053055_5.jpg'}}
  style={styles.canvas} />

Try out stretch and cover for alternative resizeModes too

brentvatne avatar Apr 21 '15 15:04 brentvatne

Here's a full example that integrates it using position: relative in the parent to constrain it:

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
} = React;

var SampleApp = React.createClass({
  render: function() {
    return (
      <View style={{flex: 1, flexDirection: 'row'}}>
        <View style={styles.container}>
          <Image
            resizeMode="contain"
            source={{uri: 'http://imgs.steps.dragoart.com/how-to-draw-a-pony-step-7_1_000000053055_5.jpg'}}
            style={styles.canvas} />
        </View>
        <View style={styles.container}>
          <Text>Hello!</Text>
        </View>
      </View>

    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    position: 'relative'
  },
  canvas: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
  },
});


AppRegistry.registerComponent('SampleApp', () => SampleApp);

screen shot 2015-04-21 at 8 56 29 am

brentvatne avatar Apr 21 '15 15:04 brentvatne

If this doesn't resolve your problem feel free to re-open.

brentvatne avatar Apr 21 '15 16:04 brentvatne

@brentvatne awesome, i actually solved it by changing the container styles around. alignItems:'center' was causing the child image element to not show for some reason.

joshbedo avatar Apr 21 '15 22:04 joshbedo

I can confirm the alignItems fix as well. In general, I find it very fiddly to figure out how combination of properties works, and the results are different depending on whether the source is local or not.

I believe that https://github.com/facebook/react-native/issues/2804#issuecomment-148723052 might be related to this also.

miracle2k avatar Oct 17 '15 12:10 miracle2k

Seems like you guys were struggeling with the same thing as me. I have an image not showing up though my code pretty much seems to be equal to @joshbedo's first post (see code below). As soon as I add a fixed height like for instance 300 to my imageWrapper style the image shows up. Does anybody have an idea?

import React, { Component, Image, PropTypes, View } from 'react-native'
import Dimensions from 'Dimensions'

let window = Dimensions.get('window')

const prefix = 'http://my-image-server.com/images/'

class MyImage extends Component {
  render() {
    let imageUrl = prefix + this.props.type + '/' + (this.props.size || 1080) + '/' + this.props.filename + '.jpg'

    return (
      <View style={styles.imageWrapper}>
        <Image style={styles.image} source={{uri: imageUrl}}/>
      </View>
    )
  }
}

MyImage.propTypes = {
  type: PropTypes.string.isRequired,
  filename: PropTypes.string.isRequired,
  size: PropTypes.string
}

let styles = {
  imageWrapper: {
    flex: 1,
    alignItems: 'stretch'
  },
  image: {
    flex: 1
  }
}

export default MyImage

oniisanlabs avatar Dec 02 '15 17:12 oniisanlabs

I have done according to this, Hope this code snippet might help you.

<Image style={styles.bgContainer} resizeMode='cover' source={require('./img/bg.png')} />

const styles = StyleSheet.create({ bgContainer: { flex:1, width: null, height: null } });

yashvekaria avatar Apr 16 '16 07:04 yashvekaria

Above @yashvekaria solution worked for me

tisalph avatar May 12 '16 22:05 tisalph

I have done without flex.

local image

<View>
  <Image
    style={{height: 100, width: null}}
    source={require('./ad.png')}
  />
</View>

network image

<View>
  <Image
    style={{height: 100}}
    source={{uri: 'http://xxx.com/ad.png'}}
  />
</View>

clinyong avatar May 18 '16 14:05 clinyong

@yashvekaria's and @clinyong's solution (adding a width: null) worked for me, and I am very curious as to why. Why is setting it to null different from not setting it at all?

mtolly avatar May 26 '16 16:05 mtolly

@clinyong How would you do width: 100%, height: auto in react-native?

vinipace avatar Jun 04 '16 21:06 vinipace

@vini175pa you can use react-native-extended-stylesheet for that, but the problem is that when the devices rotates the values are not updated...

PierBover avatar Jul 07 '16 16:07 PierBover

@vinpac try this:

Get image width and height with:

Image.getSize(path, ({ width, height }) => {
  this.setState({ width, height });
});

Then do this:

<Image
  source={{...}}
  style={{
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').width * this.state.height / this.state.width
  }}
  resizeMode={'cover'}
/>

Not a pretty way, but it works.

superandrew213 avatar Sep 23 '16 09:09 superandrew213

Hi,

I ran into the same issue as well. Some of the solutions didn't quite work for me. For instance the previous solution by @superandrew213 would have the image filling the width of the window but often you want the image to fill/respect the width of its parent container. Here's what I tried that works:

<View style={{flexDirection:'row'}}>
    <Image 
        source={...} 
        resizeMode="contain" 
        style={{flexShrink:1}}
     />
</View>

The key point is to get the image to be in a row layout using flexDirection:'row' in its container then the image has resizeMode='contain' in order for it to maintain its aspect ratio and style with flexShrink:1 to make sure it doesn't horizontally overflow its container.

ragamufin avatar Nov 16 '16 08:11 ragamufin

Hmm, I noticed that these examples only worked when a flex has been specified for all parent views/components. The image itself needs flex: 1, width: null, height: null at a minimum. Anyways this worked for me to display the image on the top half of the screen:

<View style={{flex: 1}}>
        <View style={{flexDirection: "row", flex: 1}}>
          <Image source={{uri: "https://vestigo.co/images/yoga-outside.jpg"}} style={{flex: 1, resizeMode: "stretch", width: null, height: null}}  />
        </View>
        <View style={{flex: 2}}>
        </View>
</View>

monzerhijazi avatar Nov 21 '16 20:11 monzerhijazi

@joshbedo the parent alignItems sets to center , cause the Image not show , does any one knows why? change the parent alignItems and flex:1 for the Image fix the problem for me .

dc-me avatar Feb 20 '17 08:02 dc-me

@danywheeler If you set alignItems to "center" on the parent then it changes it from the default "stretch". This causes the image then to not have any space if you don't specify a width and height

ragamufin avatar Mar 13 '17 21:03 ragamufin

@clinyong your method works great in my iOS simulator.

When I view it via Expo on my Android phone I get

Error while updating property 'width' in shadow node of type: RCTTextInlineImage

Looks like we can't use null. Stackoverflow answer here.

Your solution was so slick.. I'd like to keep using it. Ideas? Is this an Android thing?

magician11 avatar Mar 27 '17 13:03 magician11

I tried wiping out as many style options as possible and finding the minimal set of styles required to reach the goal. You don't need containers or anything, just an Image. Apparently the "width:null" bit is important:

    <Image 
      style={{ width: null }} 
      resizeMode="contain"
      source={require('./img/catfish.jpg')} 
    />

If you need it to fit with other elements:

    <Image 
      style={{ flex:1, width: null }} 
      resizeMode="contain"
      source={require('./img/catfish.jpg')} 
    />

maludwig avatar May 30 '17 06:05 maludwig

Following on from @maludwig 's solution, to get a 100% width image that has a specific height, this works:

<Image
    source={require('../images/space.jpeg')}
    style={{ height: 290, width: null }}
    resizeMode="cover"
/>

magician11 avatar May 31 '17 01:05 magician11