Как нарисовать прямоугольник с закругленными углами в React Native ART - PullRequest
1 голос
/ 28 июня 2019

Я использую библиотеку react-native ART для рисования масштабируемых векторных элементов в моем мобильном приложении, ART - это идеальная библиотека, поскольку ее можно анимировать и легко изменять с помощью собственных инструментов. Но ART не имеет пользовательских элементов, таких как SVG Circle, Rect etch ..., ART имеет только один тип с именем Shape и достаточно мощный, чтобы создавать практически любые фигуры. Но у меня возникают трудности с рисованием масштабируемого прямоугольника с закругленными углами с помощью Shape.

import React from 'react'
import PropTypes from 'prop-types'
import {ART} from 'react-native'

const {Group, Shape} = ART

export default class Graphics extends React.Component{
   render(){
      const {x, y, width, height, fill, stroke} = this.props;
      const d = `M0,0L${width},0L${width},${height}L0,${height}L0,0z`
      return(
        <Group x={x} y={y}>
           <Path d={d} fill={fill} stroke={stroke}>
        </Group>
      )
   }
}

как вы видите, я создаю прямоугольную форму с заданными шириной и высотой, но я не знаю, как генерировать закругленные углы.

Я не знаю о d3, возможно ли это сделать с помощью d3?

1 Ответ

2 голосов
/ 28 июня 2019

Вы можете использовать объект ART Path для создания путей вместе с путями curve или curveTo методов или arc arcTo методов. Пожалуйста, проверьте пример Rect компонента ниже.

import React from 'react'
import PropTypes from 'prop-types'
import {ART} from 'react-native'
const {Group, Shape, Path} = ART

function Rect({fill, stroke, x, width, y, rc, height, topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius, ...rest}){
    const startX = 0;
    const startY = 0;
    const smallDimension = width > height ? height : width;
    let tlr = topLeftRadius !== null ? topLeftRadius : rc; tlr =  tlr > smallDimension/2 ? smallDimension /2 : tlr;
    let trr = topRightRadius !== null ? topRightRadius : rc; trr = trr > smallDimension/2 ? smallDimension /2 : trr;
    let brr = bottomRightRadius !== null ? bottomRightRadius : rc; brr = brr > smallDimension/2 ? smallDimension /2 : brr;
    let blr = bottomLeftRadius !== null ? bottomLeftRadius : rc; blr = blr > smallDimension/2 ? smallDimension /2 : blr;
    const d = Path()
                .move(startX, startY)
                .move(startX, tlr)
                .arc( tlr, startY-tlr, tlr, tlr, false, false) // top left
                .lineTo(width - trr, startY)
                .arc( trr, startX+trr, trr, trr, false, false) // top right
                .lineTo(width, startY+ (height - brr))
                .arc(startX-brr, brr, brr, brr, false, false) // bottom right
                .lineTo(startX + blr, height)
                .arc(startX-blr, startY-blr, blr, blr, false, false) // bottom right
                .close()

    return(
        <Group x={x} y={y}>
            <Shape {...rest} fill={fill} stroke={stroke} d={d}/>
        </Group>
    )
}

Rect.propTypes = {
    width: PropTypes.number.isRequired,
    height: PropTypes.number.isRequired,
    x: PropTypes.number,
    y: PropTypes.number,
    fill: PropTypes.string,
    stroke: PropTypes.string,
    topLeftRadius: PropTypes.number,
    topRightRadius: PropTypes.number,
    bottomRightRadius: PropTypes.number,
    bottomLeftRadius: PropTypes.number,
    rc: PropTypes.number
}

Rect.defaultProps = {
    x: 0,
    y: 0,
    fill: 'transparent',
    stroke: 'red',
    topLeftRadius: null,
    topRightRadius: null,
    bottomRightRadius: null,
    bottomLeftRadius: null,
    rc: 0
}

export default Rect

Здесь у вас есть полностью масштабируемый независимый компонент прямоугольника поддержки закругленного угла.

  • Реквизит width & height - будет нормальный прямоугольник без закругленного угла вообще.
  • Реквизит width, height & rc - даст вам равное округленное значение угла.
  • Реквизит width, height & topRightRadius (или любой другой угол) - даст вам каждый заданный округленный угол.

Пожалуйста, проверьте это gist для полного использования. enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...