如何在React Native中制作六边形图像?

问题描述 投票:0回答:2

我想制作如下图所示的六边形图像,但没有找到任何特定的方法来定制它。

这是图片:

建议任何库使其在react-native中成为可能。

react-native
2个回答
0
投票

所以我认为六边形路径的使用是如此普遍,以至于在网上找到现有的路径将是一项简单的任务,但搜索被证明是徒劳的,所以我决定制作一个函数来制作规则的六边形 Skia 路径。我找到了一个非常酷的quora答案,关于如何获取任意大小的六边形(正六边形)的点,然后我只需连接这些点:

import {Skia} from "@shopify/react-native-skia";

function makeHexagonPath(size, offset) {
  const path = Skia.Path.Make();
  let [xOffset, yOffset] = offset || [0, 0];
  if (!size) size = 10;

  // https://www.quora.com/How-can-you-find-the-coordinates-in-a-hexagon
  const halfed = size / 2;
  const sqrt = (Math.sqrt(3) * size) / 2;
  const points = [
    [size, 0], //a
    [halfed, sqrt], //b
    [-halfed, sqrt], //c
    [-size, 0], //d
    [-halfed, -sqrt], //e
    [halfed, -sqrt], //f
  ].map(([x, y]) => [x + xOffset, y + yOffset]);
  console.log(points);
  path.moveTo(...points[0]);

  points.forEach((point) => path.lineTo(...point));
  path.close();
  return path;
}

使用

makeHexagonPath
功能,您可以绘制任意大小的剪辑,并使用偏移参数将六边形移动到所需位置:


const imageSize = 200

export default function ClipImage({imageSrc}) {
  const image = useImage(imageSrc);
  const hexagonSize = imageSize / 2;
  const path = makeHexagonPath(hexagonSize, [hexagonSize, hexagonSize]);
  if (!image) return null;
  return (
    <Group clip={path}>
      /*<Path path={path} color="lightblue" />*/
      <Image
        image={image}
        fit="cover"
        x={0}
        y={0}
        width={imageSize}
        height={imageSize}
      />
    </Group>
  );
}

我会发布一个博览会小吃来演示它,但是react-native-skia在博览会上对我不起作用,但在默认的react-native环境中它就像一个魅力


0
投票

试试这个

import React from 'react';
import {View, Image, StyleSheet, Dimensions} from 'react-native';
import Svg, {
  Defs,
  ClipPath,
  Polygon,
  Image as SvgImage,
} from 'react-native-svg';

const HexagonImage = ({imageUrl}) => {
  return (
    <View style={styles.container}>
      <Svg height="100%" width="100%" viewBox="0 0 100 100" style={styles.svg}>
        <Defs>
          <ClipPath id="hexagonClip">
            <Polygon points="50 0, 95 25, 95 75, 50 100, 5 75, 5 25" />
          </ClipPath>
        </Defs>
        <SvgImage
          href={{uri: imageUrl}}
          width="100%"
          height="100%"
          preserveAspectRatio="xMidYMid slice"
          clipPath="url(#hexagonClip)"
        />
      </Svg>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: 40, // Adjust width according to your requirements
    aspectRatio: 1, // Ensure aspect ratio is 1:1 for hexagon shape
    overflow: 'hidden',
  },
  svg: {
    position: 'absolute',
    top: 0,
    left: 0,
    // for testing purposes// for testing purposes
  },
});

export default HexagonImage;

© www.soinside.com 2019 - 2024. All rights reserved.