从2张图像中设计背景

时间:2019-08-05 15:47:29

标签: flutter background flutter-layout

我想创建一个新的无状态小部件类,该类由2个图像(顶部,底部)和一行(由函数定义,例如(x){x+500}定义),宽度(可以为0,如果它(不应该绘制)和一种颜色)将两个图像分开。

对于每个像素:

  • 如果像素的y位置大于f(x) + width/2的结果,则应绘制底部的像素
  • 如果它小于f(x) - width / 2,则应绘制一个顶部像素
  • 否则,将绘制给定线条颜色的像素

看一看mywidget({'top': A, 'bottom': B, 'f': (x){return sin(x)+500;}, 'width': 1, 'color': Color(0xFFFFFFFF)});的示例:

(0,0)
+------+
|      |
|  A   |
| __   |
|/  \__|
|      |
|  B   |
+------+(e.g. 1920,1080)

是否存在一个线形控件,其形状由(数学)函数定义?

this是唯一的方法吗?还是有一个已经允许这样做的容器小部件?我已经看过Stack widget了,但这还不能解决问题,因为如上所述,我需要一种结构来决定渲染哪个像素。决定应该发生什么的功能应该由用户提供。

1 个答案:

答案 0 :(得分:2)

ClipPathCustomClipper<Path>可以帮助您。
您会得到什么:
Result screenshot
示例源代码:

import 'dart:math';

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        body: ClippedPartsWidget(
          top: Container(
            color: Colors.red,
          ),
          bottom: Container(
            color: Colors.blue,
          ),
          splitFunction: (Size size, double x) {
            // normalizing x to make it exactly one wave
            final normalizedX = x / size.width * 2 * pi;
            final waveHeight = size.height / 15;
            final y = size.height / 2 - sin(normalizedX) * waveHeight;

            return y;
          },
        ),
      ),
    ),
  );
}

class ClippedPartsWidget extends StatelessWidget {
  final Widget top;
  final Widget bottom;
  final double Function(Size, double) splitFunction;

  ClippedPartsWidget({
    @required this.top,
    @required this.bottom,
    @required this.splitFunction,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        // I'm putting unmodified top widget to back. I wont cut it.
        // Instead I'll overlay it with clipped bottom widget.
        top,
        Align(
          alignment: Alignment.bottomCenter,
          child: ClipPath(
            clipper: FunctionClipper(splitFunction: splitFunction),
            child: bottom,
          ),
        ),
      ],
    );
  }
}

class FunctionClipper extends CustomClipper<Path> {
  final double Function(Size, double) splitFunction;

  FunctionClipper({@required this.splitFunction}) : super();

  Path getClip(Size size) {
    final path = Path();

    // move to split line starting point
    path.moveTo(0, splitFunction(size, 0));

    // draw split line
    for (double x = 1; x <= size.width; x++) {
      path.lineTo(x, splitFunction(size, x));
    }

    // close bottom part of screen
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);

    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    // I'm returning fixed 'true' value here for simplicity, it's not the part of actual question
    // basically that means that clipping will be redrawn on any changes
    return true;
  }
}