javascriptcssreact-nativetransformscaling

How can I assign an element to have a scaling transformation in percentage relative to the window in react native?


For example, I can achieve the same thing by applying the formula:

const { width } = useWindowDimension();
const porcentage = width * 0.8 (80% of the window);

<ComponentOrElement style={ width: porcentage } />

But this is based on the width (or also the height) of the element, I want to obtain the same but based on the scaling transformation. For example:

const { width } = useWindowDimension();
const porcentage = width * 0.8 (80% of the window?);

<ComponentOrElement style={ transform: [ { scale: porcentage } ] } />

Scaling has a range of 0 to 1 (or more, but it always refers to a factor, not pixels, dp, etc.).

How can I achieve this in scaling?


Solution

  • This will scale and keep the view in centre:

    const { width } = useWindowDimension();    
    
    <ComponentOrElement style={{ width: width, transform: [{ scaleX: 0.8 }] }} />
    

    Shift to right:

    const scale = .8;
    
    <ComponentOrElement
      style={{
        width: width,
        transform: [{ translateX: width * (1 - scale) * 0.5 }, { scaleX: scale }],
      }}
    />
    

    Shift to left:

    <ComponentOrElement
      style={{
        width: width,
        transform: [{ translateX: width * (scale - 1) * 0.5 }, { scaleX: scale }],
      }}
    />
    

    But they will distort the content