Как нарисовать перекрывающиеся треугольники с некоторым позиционированием во флаттере? - PullRequest
0 голосов
/ 05 мая 2020

Я хочу нарисовать несколько таких прямоугольников
enter image description here

Я использовал CustomPainter, чтобы добиться желаемого результат но получается что-то другое.
Я поделился кодом и нежелательным выходным изображением ниже. Пожалуйста, помогите мне нарисовать перекрывающиеся треугольники с некоторым позиционированием, чтобы получить желаемый результат.

import 'package:flutter/material.dart';

class SplashScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double _width = MediaQuery.of(context).size.width;
    // double _height = MediaQuery.of(context).size.height;

    return Scaffold(
      body: Container(
        width: _width,
        // height: _height,
        child: Center(
          child: Stack(children: <Widget>[
            CustomPaint(
              painter: DrawCustomRect(0, 0, 80, 112, 0xFFFA2A2A),
            ),
            CustomPaint(
              painter: DrawCustomRect(0, 0, 16, 96, 0xFFFF5454),
            ),
            CustomPaint(
              //  DrawCustomRect(_left,_top,_right, _bottom, _color);
              painter: DrawCustomRect(0, 0, 16, 80, 0xFFFF8D8D),
            ),

          ]),
        ),
      ),
    );
  }
}

class DrawCustomRect extends CustomPainter {
  final double _left;
  final double _top;
  final double _right; //width
  final double _bottom; //height
  final int _color;

  DrawCustomRect(this._left, this._top, this._right, this._bottom, this._color);

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(
      new Rect.fromLTRB(this._left, this._top, this._right, _bottom),
      new Paint()..color = new Color(_color),
    );
  }

  @override
  bool shouldRepaint(DrawCustomRect oldDelegate) {
    return false;
  }
}

this is output of below code

Ответы [ 2 ]

2 голосов
/ 05 мая 2020

Вы можете достичь этого результата, используя Контейнеры внутри стека:

Center(
  child: Stack(
    alignment: Alignment.center,
    children: <Widget>[
      Container(
        margin: EdgeInsets.only(left: 300),
        width: 75,
        height: 100,
        color: Colors.red[300],
      ),
      Container(
        margin: EdgeInsets.only(left: 150),
        width: 150,
        height: 200,
        color: Colors.red[600],
      ),
      Container(
        width: 225,
        height: 300,
        color: Colors.red[900],
      ),
    ],
  ),
),

А затем настройте размеры и цвета в зависимости от того, что вы хотите.

Результат:

result

1 голос
/ 05 мая 2020

Есть два подхода к этому. Первый и простой - использовать комбинацию виджета стека и контейнера для достижения вышеуказанного эффекта. Вот код, который я использовал

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Stack(
          children: <Widget>[
            Align(
              alignment: Alignment(0.4, 0.1),
              child: Container(
                width: 60,
                height: 60,
                color: Colors.red[200],
              ),
            ),
            Align(
              alignment: Alignment(0.3, 0.1),
              child: Container(
                width: 70,
                height: 70,
                color: Colors.red[300],
              ),
            ),
            Align(
              alignment: Alignment(0.2, 0.1),
              child: Container(
                width: 80,
                height: 80,
                color: Colors.red[400],
              ),
            ),
            Align(
              alignment: Alignment(0.1, 0.1),
              child: Container(
                width: 90,
                height: 90,
                color: Colors.red[500],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Desired effect with Container


Другой - с помощью специального рисовальщика. Вам просто нужно исправить некоторое позиционирование в своем коде.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SplashScreen(),
    );
  }
}

class SplashScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double _width = MediaQuery.of(context).size.width;
    // double _height = MediaQuery.of(context).size.height;

    return Scaffold(
      body: Container(
        width: _width,
        // height: _height,
        child: Center(
          child: Stack(
            alignment: Alignment.center,
            children: <Widget>[
              CustomPaint(
                painter: DrawCustomRect(112, 32, 0, 80, 0xFFFF8D8D),
              ),
              CustomPaint(
                painter: DrawCustomRect(96, 16, 0, 96, 0xFFFF5454),
              ),
              CustomPaint(
                painter: DrawCustomRect(80, 0, 0, 112, 0xFFFA2A2A),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class DrawCustomRect extends CustomPainter {
  final double _left;
  final double _top;
  final double _right; //width
  final double _bottom; //height
  final int _color;

  DrawCustomRect(this._left, this._top, this._right, this._bottom, this._color);

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(
      new Rect.fromLTRB(this._left, this._top, this._right, _bottom),
      new Paint()..color = new Color(_color),
    );
  }

  @override
  bool shouldRepaint(DrawCustomRect oldDelegate) {
    return false;
  }
}

Desired effect using custom painter

...