Friday, July 29, 2022

[FIXED] How to show the only part of the image

Issue

UPDATE Since the question was complicating and unclear, I'm rewriting my question to make it much simpler.

enter image description here

Given

  • image (image uri for entire image; 600x600 image from the example)
  • left(x-coordinate; 50 from the example)
  • top(y-coordinate; 100 from the example)
  • width(width of the image; 300 from the example)
  • height (height of the image; 300 from the example)

what I want

  • 300 x 300 image (which is cropped to the image)
  • 70 x 70 image (I will ultimately resized image to 70 x 70 size)

Here is my example code

// render the part of the image
console.log(left); // 50
console.log(thumbSize); // 300
return (
        <Image
          source={{uri: image}}
          style={selectedStyle(left, top, thumbSize)}/>
      );
... 
function selectedStyle(left, top, thumbSize) {
  return {
    left,
    top,
    width: thumbSize,
    height: thumbSize
  };
}

UPDATE from zvona's working demo, what I want is this.

enter image description here but nothing else.

enter image description here


Solution

Here is a working example: https://snack.expo.io/@zvona/cropped-image

The idea is to have "cropped" View where Image is positioned inside it with custom dimensions. I use constants in my example to clarify the case.

<View style={styles.cropped}>
  <Image
    style={styles.image}
    source={{uri: 'https://upload.wikimedia.org/wikipedia/en/0/02/Homer_Simpson_2006.png'}} />
</View>

And on styles:

  image: {
    marginLeft: -OFFSET_LEFT,
    marginTop: -OFFSET_TOP,
    width: IMAGE_WIDTH,
    height: IMAGE_HEIGHT,
  },

  cropped: {
    width: 150,
    height: 150,
    overflow: 'hidden',
    position: 'absolute',
    left: OFFSET_LEFT,
    top: OFFSET_TOP,
  },

Note that ImageBackground is only for example purposes and it's not needed in the actual implementation.



Answered By - Samuli Hakoniemi
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.