Search code examples
react-nativereact-animated

How do I calculate the offset of a scaled image?


I use Animated on an image to scale the image programatically when the user presses a button.

  handleZoomIn() {
    this.zoom += -0.25;
    Animated.spring(this.animatedValue, {
      toValue: this.zoom
    }).start()   }

  handleZoomOut() {
    this.zoom += 0.25;
    Animated.spring(this.animatedValue, {
      toValue: this.zoom,
      friction: 3,
      tension: 40
    }).start()   }
    const imageStyle = {
      transform: [{ scale: this.animatedValue}]
    } 

   render() {
      <Animated.Image source={{ uri: source }} style={[imgSize, { position: 'absolute' }, imageStyle]} />
   }

There is a image and a scaled image. enter image description here

How do I calculate the distance between the top-left corner of the two images?

Shouldn't the offset be?

(dx, dy) = ((originalWidth-(originalWidth X scale))/2, (originalWidth - (originalHeight X scale))/2)


Solution

  • (dx, dy) = ((originalWidth-(originalWidth X scale))/2, (originalWidth - (originalHeight X scale))/2)

    Basically yes, but you have copy/paste typo of using "width" in height also, i.e.: (dx, dy) = ((originalWidth-(originalWidth * scale))/2, (originalHeight - (originalHeight * scale))/2)

    And that can be somewhat simplified (? personal bias probably) in classic procedural code, something like:

    offsetFactor = (1.0 - scale) / 2;
    dx = originalWidth * offsetFactor;
    dy = originalHeight * offsetFactor;
    

    How do I calculate the distance between the top-left corner of the two images?

    Oh, but your question was about distance.. then that's of course d = sqrt((dx*dx) + (dy*dy)); ... but half of the time programmers needs this one, the squared distance (d_sq = (dx*dx) + (dy*dy);) is enough, for example for sorting, or checking if something is within radius (then you compare against squared radius value), etc... one can avoid root calculation then, which is often major optimization in case there's lot of values involved. (one of the cases where this doesn't fly is the light shading model in 3D, which made the "phong shading" quite an expensive feature of early 3D renderers, as you can't avoid at least inaccurate root calculation per-pixel there)