Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically align top with resize mode cover in images - react native

Tags:

react-native

I have a rectangular image with height greater than width. So resizeMode='cover' is used. It keeps the aspect ratio equal but expands from the center and top portion of the image is not seen. What I am trying to do is to keep the aspect ratio and show the image from the top.

Please try the code in the snack: https://snack.expo.io/@codebyte99/new-addition-to-home-page

code:

<View>
    <Image
      source={{
        uri:
          'https://img.kpopmap.com/2017/09/HanYeSul-min.jpg',
      }}
      resizeMode={'cover'}
      style={{ width: 120, height: 120 }}
    />
 </View>

Image now

enter image description here

Image what I want to achieve

enter image description here

Image original

enter image description here

I want to align the image from the top so that the head section is seen clearly. We can do that in css by object-fit: cover and object-position: top but how can it be done in react native?

like image 632
Amrita Stha Avatar asked Oct 23 '19 14:10

Amrita Stha


1 Answers

You can try to use ImageBackground and some overflow hidden like this:

import * as React from 'react';
import { Text, View, StyleSheet, ImageBackground } from 'react-native';
import Constants from 'expo-constants';


export default function App() {
  return (
    <View style={styles.container}>
      <View styles={styles.imageContainer}>
        <ImageBackground
           source={{uri: 'https://i.stack.imgur.com/n5xcc.jpg'}}
            style={{
              height: 200, // <-- you can adjust visible area
              width: 200,  // <-- same here
              overflow: 'hidden'
            }}
            imageStyle={{
              resizeMode: "cover",
              height: 260, // <-- you can adjust this height to play with zoom
            }}
        >
        </ImageBackground>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: 'pink',
    alignItems: 'center',
    padding: 8,
  },
});

Result should be something like this:

enter image description here

like image 138
Florin Dobre Avatar answered Oct 06 '22 02:10

Florin Dobre