react-native#PixelRatio TypeScript Examples

The following examples show how to use react-native#PixelRatio. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: machine.context.ts    From companion-kit with MIT License 6 votes vote down vote up
getScrollContainerHeight(baseView?: Partial<PersonaViewState>): { height: number, view: PersonaViewState } {
        const dh = Layout.window.height;
        const personaRadius = this.personaRadius;
        const pixelRatio = PixelRatio.get();

        const view: PersonaViewState = {
            scale: 1,
            rotation: 45,
            ...baseView,
            position: {
                x: 0,
                y: dh * pixelRatio / 2,
            },
            anchorPoint: { x: 0, y: 0 },
            debugName: 'SETUP_SCROLL',
        };

        const availableHeight = dh - personaRadius / pixelRatio;

        logger.log('[PersonaViewContext] getScrollContainerHeight', { personaRadius, availableHeight, pixelRatio });

        return {
            height: availableHeight,
            view: view,
        };
    }
Example #2
Source File: utils.ts    From iotc-cpm-sample with MIT License 6 votes vote down vote up
export function normalize(size: number) {
  const newSize = size * scale;
  if (Platform.OS === 'ios') {
    return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 1;
  } else {
    return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2;
  }
}
Example #3
Source File: screen-util.ts    From beancount-mobile with MIT License 6 votes vote down vote up
onePx = 1 / PixelRatio.get()
Example #4
Source File: module.ts    From react-native-keyboard-area with MIT License 6 votes vote down vote up
/**
   * This is private method handling the native event listener logic
   * When fired it will invoke all the previously registered callbacks
   * @param height current keyboard height
   */
  private static keyboardListener(height: number) {
    const keyboardHeight =
      Platform.OS === 'android' ? height / PixelRatio.get() : height;
    RNKeyboard.callbacks.forEach(callback => {
      callback(keyboardHeight);
    });
  }
Example #5
Source File: index.tsx    From frontatish with MIT License 5 votes vote down vote up
scaleDimension = (dimension: number, base = 'width') => {
  const { width: screenWidth, height: screenHeight } = Dimensions.get('screen');
  const scale = base === 'width' ? screenWidth / 375 : screenHeight / 667; // viewport of iphone se 2nd gen
  const scaledDim = dimension * scale;
  return Math.round(PixelRatio.roundToNearestPixel(scaledDim));
}
Example #6
Source File: machine.context.ts    From companion-kit with MIT License 5 votes vote down vote up
getContainerHeight(minHeight: number, baseView?: Partial<PersonaViewState>): { height: number, view: PersonaViewState } {
        const pixelRatio = PixelRatio.get();
        const dh = Layout.window.height;
        const boxSize = this.personaBoxHeight;
        const notEnoughSpace = (minHeight + boxSize) > dh;
        const offset = dh - boxSize - minHeight;
        const personaRadius = this.personaRadius;
        const limit = boxSize * 0.38;

        // default view state
        const view: PersonaViewState = {
            scale: 1,
            rotation: 45,
            ...baseView,
            position: { x: 0, y: 0 },
            anchorPoint: { x: 0, y: 0 },
        };
        let availableHeight: number;

        if (notEnoughSpace) {
            // logger.log('not enough space. move persona up.');
            if (Math.abs(offset) > limit) {
                view.position.y = dh * pixelRatio / 2;
                view.debugName = 'SETUP_HALF_OUT';

                availableHeight = dh - personaRadius / pixelRatio;
            } else {
                view.position.y = (minHeight - dh / 2) * pixelRatio;
                view.anchorPoint.y = 1;
                view.debugName = 'SETUP_PARTIAL';

                availableHeight = minHeight;
            }
        } else {
            view.position.y = (dh / 2 - boxSize) * pixelRatio;
            view.anchorPoint.y = 1;
            view.debugName = 'SETUP_FULL_SIZE';

            // logger.log('persona position is ok. scale up content.');
            availableHeight = minHeight + offset;
        }

        logger.log('[PersonaViewContext] getContainerHeight', { personaRadius, notEnoughSpace, minHeight, offset, limit, availableHeight, pixelRatio });

        return {
            height: availableHeight,
            view: view,
        };
    }
Example #7
Source File: single-code-input.tsx    From protect-scotland with Apache License 2.0 5 votes vote down vote up
SingleCodeInput: React.FC<SingleCodeInputProps> = ({
  style,
  disabled = false,
  autoFocus = false,
  onChange,
  error,
  count,
  accessibilityHint,
  accessibilityLabel
}) => {
  const [value, setValue] = useState<string>('');
  const inputRef = createRef<TextInput>();
  const fontScale = PixelRatio.getFontScale();

  useEffect(() => {
    const isScreenReaderEnabled = (async function () {
      await AccessibilityInfo.isScreenReaderEnabled();
    })();
    if (autoFocus && !isScreenReaderEnabled) {
      inputRef.current?.focus();
    }
  }, [inputRef, autoFocus]);

  const onChangeTextHandler = (v: string) => {
    const validatedValue = v.replace(/[^a-zA-Z0-9]/g, '');
    setValue(validatedValue);

    if (!validatedValue) {
      return;
    }

    if (onChange) {
      onChange(validatedValue);
    }
  };

  const onFocusHandler = () => {
    if (error) {
      inputRef.current?.clear();
      inputRef.current?.focus();
      if (onChange) {
        onChange(value);
      }
    }
  };

  return (
    <View style={[styles.container, style]}>
      <TextInput
        ref={inputRef}
        selectTextOnFocus
        autoCapitalize="characters"
        style={[
          styles.input,
          {height: 60 * fontScale},
          error ? styles.errorBlock : styles.block
        ]}
        maxLength={count}
        keyboardType="default"
        returnKeyType="done"
        editable={!disabled}
        value={value}
        placeholder="——————"
        onFocus={onFocusHandler}
        onChangeText={onChangeTextHandler}
        accessibilityLabel={accessibilityLabel}
        accessibilityHint={accessibilityHint}
      />
    </View>
  );
}
Example #8
Source File: responsive.ts    From react-native-tiktok-clone with MIT License 5 votes vote down vote up
normalize = (size: number) => {
  const newSize = size * scale;
  if (Platform.OS === 'ios') {
    return Math.round(PixelRatio.roundToNearestPixel(newSize));
  } else {
    return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2;
  }
}
Example #9
Source File: AssetSources.ts    From nlw2-proffy with MIT License 5 votes vote down vote up
/**
 * Selects the best file for the given asset (ex: choosing the best scale for images) and returns
 * a { uri, hash } pair for the specific asset file.
 *
 * If the asset isn't an image with multiple scales, the first file is selected.
 */
export function selectAssetSource(meta: AssetMetadata): AssetSource {
  // Override with the asset map in manifest if available
  if (assetMapOverride && assetMapOverride.hasOwnProperty(meta.hash)) {
    meta = { ...meta, ...assetMapOverride[meta.hash] };
  }

  // This logic is based on that of AssetSourceResolver, with additional support for file hashes and
  // explicitly provided URIs
  const scale = AssetSourceResolver.pickScale(meta.scales, PixelRatio.get());
  const index = meta.scales.findIndex(s => s === scale);
  const hash = meta.fileHashes ? meta.fileHashes[index] || meta.fileHashes[0] : meta.hash;

  // Allow asset processors to directly provide the URL to load
  const uri = meta.fileUris ? meta.fileUris[index] || meta.fileUris[0] : meta.uri;
  if (uri) {
    return { uri: resolveUri(uri), hash };
  }

  // Check if the assetUrl was overridden in the manifest
  const assetUrlOverride = getManifest().assetUrlOverride;
  if (assetUrlOverride) {
    const uri = path.join(assetUrlOverride, hash);
    return { uri: resolveUri(uri), hash };
  }

  const fileScale = scale === 1 ? '' : `@${scale}x`;
  const fileExtension = meta.type ? `.${encodeURIComponent(meta.type)}` : '';
  const suffix = `/${encodeURIComponent(
    meta.name
  )}${fileScale}${fileExtension}?platform=${encodeURIComponent(
    Platform.OS
  )}&hash=${encodeURIComponent(meta.hash)}`;

  // For assets with a specified absolute URL, we use the existing origin instead of prepending the
  // development server or production CDN URL origin
  if (/^https?:\/\//.test(meta.httpServerLocation)) {
    const uri = meta.httpServerLocation + suffix;
    return { uri, hash };
  }

  // For assets during development, we use the development server's URL origin
  if (getManifest().developer) {
    const baseUrl = new URL(getManifest().bundleUrl);
    baseUrl.set('pathname', meta.httpServerLocation + suffix);
    return { uri: baseUrl.href, hash };
  }

  // Production CDN URIs are based on each asset file hash
  return {
    uri: `https://d1wp6m56sqw74a.cloudfront.net/~assets/${encodeURIComponent(hash)}`,
    hash,
  };
}
Example #10
Source File: Home.tsx    From lexicon with MIT License 5 votes vote down vote up
fontScale = PixelRatio.getFontScale()
Example #11
Source File: CreditCard.tsx    From react-native-credit-card-form-ui with MIT License 5 votes vote down vote up
styles = StyleSheet.create({
  cardWrapper: {
    height: '100%',
    maxHeight: 220,
    position: 'relative',
    width: '100%',
    maxWidth: 350,
    shadowColor: 'rgba(0,0,0,0.6)',
    shadowOffset: {
      width: 0,
      height: 6,
    },
    shadowOpacity: 0.37,
    shadowRadius: 7.49,
    borderRadius: 6,
    justifyContent: 'center',
    alignItems: 'center',
  },

  background: {
    resizeMode: 'cover',
    width: '100%',
    height: '100%',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 8,
  },
  textLabel: {
    fontSize: 10 / PixelRatio.getFontScale(),
    textTransform: 'uppercase',
  },
  textData: {
    fontWeight: 'bold',
    fontSize: 16 / PixelRatio.getFontScale(),
    marginTop: Platform.OS == 'android' ? -10 : undefined,
    marginLeft: Platform.OS == 'android' ? -4 : undefined,
  },
  textCardNumber: {
    fontSize: 20 / PixelRatio.getFontScale(),
    fontWeight: 'bold',
    marginBottom: 8,
    marginTop: Platform.OS == 'ios' ? 16 : 5,
    letterSpacing: 2,
  },
  imageChip: {
    marginTop: 16,
  },
  footer: {
    marginTop: Platform.OS == 'ios' ? 16 : 5,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  strip: {
    backgroundColor: 'rgba(0,0,0,.6)',
    position: 'absolute',
    left: 0,
    right: 0,
    marginTop: 48,
    height: 40,
  },
  cvvWrapper: {
    height: '100%',
    alignItems: 'flex-end',
    justifyContent: 'flex-end',
    bottom: 24,
  },
  holderWrapper: {
    flex: 2,
    marginRight: 16,
  },
  expirationWrapper: {
    flex: 1,
    alignItems: 'flex-end',
  },
})
Example #12
Source File: index.tsx    From react-native-bottomsheet-reanimated with MIT License 5 votes vote down vote up
normalize = (height: number) => {
  if (typeof height === 'number') {
    return height;
  } else {
    const elemHeight = parseFloat(height);
    return PixelRatio.roundToNearestPixel((Screen.height * elemHeight) / 100);
  }
}
Example #13
Source File: grid.tsx    From protect-scotland with Apache License 2.0 4 votes vote down vote up
Grid: FC<Grid> = ({
  onboarded,
  stage,
  opacity,
  onboardingCallback
}) => {
  const {contacts, enabled, status} = useExposure();
  const {paused} = useReminder();
  const {isolationDuration} = useSettings();
  const hasContact = hasCurrentExposure(isolationDuration, contacts);
  const active = enabled && status.state === StatusState.active;
  const fontScale = PixelRatio.getFontScale();

  const tracingIcon = hasContact
    ? ContactTracingIcon
    : paused
    ? PausedIcon
    : active
    ? TracingIcon
    : InactiveTracingIcon;

  const tracingLabel = hasContact
    ? 'dashboard:tracing:contact'
    : paused
    ? 'dashboard:tracing:paused'
    : 'dashboard:tracing:label';

  const tracingHint = hasContact
    ? 'dashboard:tracing:contactHint'
    : paused
    ? 'dashboard:tracing:pausedHint'
    : active
    ? 'dashboard:tracing:active'
    : 'dashboard:tracing:inactive';

  const tracingBackground = hasContact
    ? colors.errorRed
    : paused
    ? colors.lightGray
    : active
    ? colors.validationGreen
    : colors.darkGrey;

  if (!onboarded) {
    return (
      <Animated.View style={[styles.container, {opacity}]}>
        <View style={styles.column}>
          {stage === 0 && (
            <Tile
              backgroundColor={tracingBackground}
              label={tracingLabel}
              hint={tracingHint}
              image={tracingIcon}
              minHeight={195}
              link={ScreenNames.tracing}
              onboardingCallback={onboardingCallback}
            />
          )}
          {stage === 2 && (
            <Tile
              backgroundColor={colors.pink}
              label="dashboard:about:label"
              image={CommentIcon}
              link={ScreenNames.about}
              onboardingCallback={onboardingCallback}
            />
          )}
          {stage === 1 && (
            <Tile
              backgroundColor={colors.lilac}
              label="dashboard:community:label"
              image={CommunityIcon}
              link={ScreenNames.community}
              onboardingCallback={onboardingCallback}
            />
          )}
          {stage === 3 && (
            <Tile
              backgroundColor={colors.resultYellow}
              label="dashboard:test:label"
              hint="dashboard:test:hint"
              dark
              image={JarIcon}
              minHeight={195}
              link={ScreenNames.tests}
              onboardingCallback={onboardingCallback}
            />
          )}
        </View>
        {fontScale <= 1 && (
          <>
            <View style={styles.spacer} />
            <View style={styles.column} />
          </>
        )}
      </Animated.View>
    );
  }

  const Stage1 = () => (
    <Tile
      backgroundColor={tracingBackground}
      label={tracingLabel}
      hint={hasContact ? undefined : tracingHint}
      image={tracingIcon}
      minHeight={195}
      link={ScreenNames.tracing}
      additionalLabel={hasContact ? 'dashboard:tracing:contactHint' : undefined}
    />
  );

  const Stage2 = () => (
    <Tile
      backgroundColor={colors.pink}
      label="dashboard:about:label"
      image={CommentIcon}
      link={ScreenNames.about}
    />
  );

  const Stage3 = () => (
    <Tile
      backgroundColor={colors.lilac}
      label="dashboard:community:label"
      image={CommunityIcon}
      link={ScreenNames.community}
    />
  );

  const Stage4 = () => (
    <Tile
      backgroundColor={colors.resultYellow}
      label="dashboard:test:label"
      hint="dashboard:test:hint"
      dark
      image={JarIcon}
      minHeight={195}
      link={ScreenNames.tests}
    />
  );

  if (fontScale <= 1.6) {
    return (
      <View style={styles.container}>
        <View style={styles.column}>
          <Stage1 />
          <Spacing s={15} />
          <Stage2 />
        </View>
        <View style={styles.spacer} />
        <View style={styles.column}>
          <Stage3 />
          <Spacing s={15} />
          <Stage4 />
        </View>
      </View>
    );
  }

  return (
    <View style={styles.largeFontColumn}>
      <Stage1 />
      <Spacing s={15} />
      <Stage2 />
      <Spacing s={15} />
      <Stage3 />
      <Spacing s={15} />
      <Stage4 />
    </View>
  );
}