react-native 1px 解决方案

2023-11-16  本文已影响0人  暴躁程序员

方式一:通过 PixelRatio.get() 获取到手机的像素比,设置边框宽度时除以像素比

import * as React from 'react';
import {View, Text, StyleSheet, PixelRatio} from 'react-native';

function App() {
  return (
    <View style={styles.container}>
      <View style={styles.border1}>
        <Text>边框1像素解决方案</Text>
      </View>
      <View style={styles.footer}>
        <Text style={[styles.footerText, styles.Divider]}>底部分割线</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  // 1 像素边框
  border1: {
    margin: 20,
    height: 200,
    borderStyle: 'solid',
    borderColor: '#ccc',
    borderWidth: 1 / PixelRatio.get(),
  },
  footer: {
    height: 50,
    margin: 20,
  },
  footerText: {
    height: 50,
    textAlign: 'center',
    textAlignVertical: 'center',
    includeFontPadding: false,
  },
  // 1 像素分割线
  Divider: {
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#ccc',
  },
});
export default App;

方式二:通过 StyleSheet.hairlineWidth 定义宽度

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

function App() {
  return (
    <View style={styles.container}>
      <View style={styles.border1}>
        <Text>边框1像素解决方案</Text>
      </View>
      <View style={styles.footer}>
        <Text style={[styles.footerText, styles.Divider]}>底部分割线</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  // 1 像素边框
  border1: {
    margin: 20,
    height: 200,
    borderStyle: 'solid',
    borderColor: '#ccc',
    borderWidth: StyleSheet.hairlineWidth,
  },
  footer: {
    height: 50,
    margin: 20,
  },
  footerText: {
    height: 50,
    textAlign: 'center',
    textAlignVertical: 'center',
    includeFontPadding: false,
  },
  // 1 像素分割线
  Divider: {
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#ccc',
  },
});
export default App;
上一篇 下一篇

猜你喜欢

热点阅读