tools.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import Taro from "@tarojs/taro";
  2. export function alphaToHex(alpha) {
  3. var alphaValue = Math.round(alpha * 255); // 将透明度乘以255并四舍五入
  4. var hexValue = alphaValue.toString(16); // 将整数转换为十六进制字符串
  5. if (hexValue.length === 1) {
  6. hexValue = "0" + hexValue; // 如果十六进制字符串只有一位,补零
  7. }
  8. return hexValue;
  9. }
  10. export function rgbaToRgb(rgba) {
  11. if (rgba.startsWith("rgba")) {
  12. // 提取 RGBA 值
  13. const regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+(\.\d+)?)\s*\)/;
  14. const matches = rgba.match(regex);
  15. if (matches && matches.length === 6) {
  16. const red = parseInt(matches[1]);
  17. const green = parseInt(matches[2]);
  18. const blue = parseInt(matches[3]);
  19. const alpha = parseFloat(matches[4]);
  20. // 计算 RGB 值
  21. const rgbRed = Math.round(red * alpha);
  22. const rgbGreen = Math.round(green * alpha);
  23. const rgbBlue = Math.round(blue * alpha);
  24. return `rgb(${rgbRed}, ${rgbGreen}, ${rgbBlue})`;
  25. }
  26. }
  27. // 如果无法解析或不是 RGBA 值,则返回原始值
  28. return rgba;
  29. }
  30. export function rpxToPx(n: number) {
  31. var rate = Taro.getSystemInfoSync().windowWidth / 750;
  32. return n * rate;
  33. }
  34. export function vibrate(type?: string) {
  35. if (process.env.TARO_ENV == 'rn') {
  36. const ReactNativeHapticFeedback = require("react-native-haptic-feedback")
  37. // Optional configuration
  38. const options = {
  39. enableVibrateFallback: true,
  40. ignoreAndroidSystemSettings: false,
  41. };
  42. // Trigger haptic feedback
  43. ReactNativeHapticFeedback.trigger("impactLight", options);
  44. }
  45. else {
  46. Taro.vibrateShort({
  47. type: 'medium'
  48. })
  49. }
  50. }
  51. //微信sdk版本比较
  52. export function compareVersion(v1, v2) {
  53. v1 = v1.split('.')
  54. v2 = v2.split('.')
  55. const len = Math.max(v1.length, v2.length)
  56. while (v1.length < len) {
  57. v1.push('0')
  58. }
  59. while (v2.length < len) {
  60. v2.push('0')
  61. }
  62. for (let i = 0; i < len; i++) {
  63. const num1 = parseInt(v1[i])
  64. const num2 = parseInt(v2[i])
  65. if (num1 > num2) {
  66. return 1
  67. } else if (num1 < num2) {
  68. return -1
  69. }
  70. }
  71. return 0
  72. }
  73. export function getTimezone() {
  74. var split = new Date().toString().split(' ');
  75. var timeZoneFormatted = '';
  76. split.map(item => {
  77. if (item.indexOf('GMT') != -1) {
  78. timeZoneFormatted = item;
  79. }
  80. })
  81. return timeZoneFormatted;
  82. }
  83. export function getTimezoneName(){
  84. var split = new Date().toString().split('(');
  85. if (split.length < 2) {
  86. return '';
  87. }
  88. return split[1].split(')')[0];
  89. }