Created
June 21, 2024 10:08
-
-
Save davidtran/443d8401626daa16d1b5f6ebc127eadc to your computer and use it in GitHub Desktop.
Draw an arrow in React Native to connect 2 elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { View, StyleSheet, LayoutRectangle } from 'react-native'; | |
import Svg, { Line, Polygon } from 'react-native-svg'; | |
interface ArrowProps { | |
start: LayoutRectangle; | |
end: LayoutRectangle; | |
} | |
const Arrow: React.FC<ArrowProps> = ({ start, end }) => { | |
const startX = start.x + start.width / 2; | |
const startY = start.y + start.height / 2; | |
const endX = end.x + end.width / 2; | |
const endY = end.y + end.height / 2; | |
const arrowHeadSize = 10; | |
const angle = Math.atan2(endY - startY, endX - startX); | |
const arrowHeadX1 = endX - arrowHeadSize * Math.cos(angle - Math.PI / 6); | |
const arrowHeadY1 = endY - arrowHeadSize * Math.sin(angle - Math.PI / 6); | |
const arrowHeadX2 = endX - arrowHeadSize * Math.cos(angle + Math.PI / 6); | |
const arrowHeadY2 = endY - arrowHeadSize * Math.sin(angle + Math.PI / 6); | |
return ( | |
<Svg style={[StyleSheet.absoluteFill, { zIndex: 9999}]}> | |
<Line | |
x1={startX} | |
y1={startY} | |
x2={endX} | |
y2={endY} | |
stroke="#fff" | |
strokeWidth="2" | |
/> | |
<Polygon | |
points={`${endX},${endY} ${arrowHeadX1},${arrowHeadY1} ${arrowHeadX2},${arrowHeadY2}`} | |
fill="#fff" | |
/> | |
</Svg> | |
); | |
}; | |
export default Arrow; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment