Flutter实现矩形取色器的封装

前言

最近看插件库上少有的取色器大都是圆形的或者奇奇怪的的亚子,所以今天做两个矩形的颜色取色器

提示:以下是本篇文章正文内容,下面案例可供参考

一、BarTypeColorPicker

条形选色板的功能实现,颜色的获取是通过位置来判断,然后赋予相应的颜色。这个封装好的组件可通过colorListener、onTapUpListener的回调方法,把颜色传出去。

代码如下(示例):

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

///描述:条形选色板

class BarTypeColorPicker extends StatefulWidget {
  final Color initialColor;
  final ValueChanged<Color> colorListener;
  final ValueChanged<Color> onTapUpListener;
  final int colorWidth;
  final int colorHeight;
  final Color color;

  const BarTypeColorPicker(
      {Key key,
      this.initialColor,
      this.colorListener,
      this.onTapUpListener,
      this.colorWidth,
      this.colorHeight,
      this.color})
      : super(key: key);

  @override
  _BarTypeColorPickerState createState() => _BarTypeColorPickerState(
        colorWidth.toDouble(),
        colorHeight.toDouble(),
      );
}

class _BarTypeColorPickerState extends State<BarTypeColorPicker> {
  double _top = 0.0;
  double _left = 0.0;
  double _Thumbsize = 20;
  double lightness;
  double _colorwidth;
  double _colorHeight;
  Color _color;

  _BarTypeColorPickerState(double colorwidth, double colorHeight) {
    this._colorwidth = colorwidth;
    this._colorHeight = colorHeight;
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        onPanStart: (DragStartDetails detail) {
          var localPosition = detail.localPosition;
          buildSetState(localPosition, context);
          if (widget.colorListener != null) {
            widget.colorListener(_color);
          }
        },
        onPanDown: (DragDownDetails detail) {
          var localPosition = detail.localPosition;
          buildSetState(localPosition, context);
          if (widget.colorListener != null) {
            widget.colorListener(_color);
          }
        },
        onPanUpdate: (DragUpdateDetails detail) {
          var localPosition = detail.localPosition;
          buildSetState(localPosition, context);
          if (widget.colorListener != null) {
            widget.colorListener(_color);
          }
        },
        onPanEnd: (DragEndDetails detail) {
          if (widget.onTapUpListener != null) {
            widget.onTapUpListener(_color);
          }
        },
        onTapUp: (TapUpDetails detail) {
          if (widget.onTapUpListener != null) {
            widget.onTapUpListener(_color);
          }
        },
        child: ColorRect(
            colorHeight: _colorHeight,
            colorwidth: _colorwidth,
            top: _top,
            Thumbsize: _Thumbsize,
            left: _left,
            color: _color),
      ),
    );
  }

  void buildSetState(Offset localPosition, BuildContext context) {
    return setState(() {
      _left = localPosition.dx;
      _top = localPosition.dy;
      if (_left < 0) {
        _left = 0;
      } else if (0 <= _left && _left <= _colorwidth) {
        _left = _left;
      } else if (_left > _colorwidth) {
        _left = (_colorwidth);
      }
      if ((_colorwidth / 7) * 0 < _left && _left < (_colorwidth / 7) * 1) {
        _color = Color(0xFFFF0000);
      } else if ((_colorwidth / 7) * 1 < _left &&
          _left < (_colorwidth / 7) * 2) {
        _color = Color(0xFFFFFF00);
      } else if ((_colorwidth / 7) * 2 < _left &&
          _left < (_colorwidth / 7) * 3) {
        _color = Color(0xFF00FF00);
      } else if ((_colorwidth / 7) * 3 < _left &&
          _left < (_colorwidth / 7) * 4) {
        _color = Color(0xFF00FFFF);
      } else if ((_colorwidth / 7) * 4 < _left &&
          _left < (_colorwidth / 7) * 5) {
        _color = Color(0xFF0000FF);
      } else if ((_colorwidth / 7) * 5 < _left &&
          _left < (_colorwidth / 7) * 6) {
        _color = Color(0xFFFF00FF);
      } else if ((_colorwidth / 7) * 6 < _left &&
          _left < (_colorwidth / 7) * 7) {
        _color = Color(0xFFFFFFFF);
      }
      if (_top <= 0) {
        _top = 0;
      } else if (0 <= _top && _top <= _colorHeight) {
      } else if (_top > _colorHeight) {
        _top = _colorHeight;
      }
    });
  }
}

class ColorRect extends StatelessWidget {
  ColorRect({
    Key key,
    @required double colorHeight,
    @required double colorwidth,
    @required double top,
    @required double Thumbsize,
    @required double left,
    @required Color color,
  })  : _colorHeight = colorHeight,
        _colorwidth = colorwidth,
        _top = top,
        _Thumbsize = Thumbsize,
        _left = left,
        _color = color,
        super(key: key);

  final double _colorHeight;
  final double _colorwidth;
  final double _top;
  final double _Thumbsize;
  final double _left;
  final Color _color;
  List<Color> colorList = [
    Color(0xFFFF0000),
    Color(0xFFFFFF00),
    Color(0xFF00FF00),
    Color(0xFF00FFFF),
    Color(0xFF0000FF),
    Color(0xFFFF00FF),
    Color(0xFFFFFFFF),
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      width: _colorwidth,
      height: _colorHeight,
      child: Stack(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: colorList
                .map(
                  (e) => Container(
                    padding: EdgeInsets.symmetric(horizontal: 2),
                    height: _colorHeight,
                    width: _colorwidth / 7,
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: e,
                      ),
                    ),
                  ),
                )
                .toList(),
          ),
          Container(
              child: Thumb(
                  top: _top,
                  Thumbsize: _Thumbsize,
                  left: _left,
                  color: _color)),
        ],
      ),
    );
  }
}

class Thumb extends StatelessWidget {
  const Thumb({
    Key key,
    @required double top,
    @required double Thumbsize,
    @required double left,
    @required Color color,
  })  : _top = top,
        _Thumbsize = Thumbsize,
        _left = left,
        _color = color,
        super(key: key);

  final double _top;
  final double _Thumbsize;
  final double _left;
  final Color _color;

  @override
  Widget build(BuildContext context) {
    return Positioned(
        top: _top - _Thumbsize / 2,
        left: _left - _Thumbsize / 2,
        child: GestureDetector(
            child: Container(
          child: Icon(
            Icons.circle,
            color: _color,
            size: _Thumbsize,
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                blurRadius: 0.1, //阴影范围
                spreadRadius: 0.001, //阴影浓度
                color: Colors.black, //阴影颜色
              ),
            ],
          ),
        )));
  }
}

下面是使用方法。

BarTypeColorPicker(
   initialColor: Colors.white,
   colorWidth: 360,
   colorHeight: 150,
),

具体效果图:

一、RectangleColorPicker

矩形选色板的功能实现,颜色的获取是通过位置的坐标值转换为相应的颜色。这个封装好的组件可通过colorListener、onTapUpListener的回调方法,把颜色传出去。

代码如下(示例):

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class RectangleColorPicker extends StatefulWidget {
  final Color initialColor;
  final ValueChanged<Color> colorListener;
  final ValueChanged<Color> onTapUpListener;
  final int colorWidth;
  final int colorHeight;
  final Color color;

  const RectangleColorPicker(
      {Key key,
      this.initialColor,
      this.colorListener,
      this.onTapUpListener,
      this.colorWidth,
      this.colorHeight,
      this.color})
      : super(key: key);

  @override
  _RectangleColorPickerState createState() => _RectangleColorPickerState(
        colorWidth.toDouble(),
        colorHeight.toDouble(),
      );
}

class _RectangleColorPickerState extends State<RectangleColorPicker> {
  double _top = 0.0;
  double _left = 0.0;
  double _Thumbsize = 20;
  double _hue = 0.0;
  double _brightnum = 50.0;
  double lightness;
  double _colorwidth;
  double _colorHeight;

  _RectangleColorPickerState(double colorwidth, double colorHeight) {
    this._colorwidth = colorwidth;
    this._colorHeight = colorHeight;
  }

  Color get _color {
    return HSLColor.fromAHSL(
      1,
      _hue,
      1,
      lightness,
    ).toColor();
    //返回HSL、AHSL格式的色调亮度字符串
  }

  @override
  void initState() {
    super.initState();
    HSLColor hslColor = HSLColor.fromColor(widget.initialColor);
    _left = (_colorwidth * hslColor.hue) / 360;
    _top = (_colorHeight * (hslColor.lightness - 0.5) * 200) / 100;
    this._hue = hslColor.hue;
    this.lightness = hslColor.lightness;
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        onPanStart: (DragStartDetails detail) {
          var localPosition = detail.localPosition;
          buildSetState(localPosition, context);
          if(widget.colorListener != null){
            widget.colorListener(_color);
          }

        },
        onPanDown: (DragDownDetails detail) {
          var localPosition = detail.localPosition;
          buildSetState(localPosition, context);
          if(widget.colorListener != null){
            widget.colorListener(_color);
          }
        },
        onPanUpdate: (DragUpdateDetails detail) {
          //获取当前触摸点的局部坐标
          var localPosition = detail.localPosition;
          buildSetState(localPosition, context);
          if(widget.colorListener != null){
            widget.colorListener(_color);
          }

        },
        onPanEnd: (DragEndDetails detail) {
          if(widget.onTapUpListener != null){
            widget.onTapUpListener(_color);
          }
        },
        onTapUp: (TapUpDetails detail){
          if(widget.onTapUpListener != null){
            widget.onTapUpListener(_color);
          }
        },
        child: ColorRect(
            colorHeight: _colorHeight,
            colorwidth: _colorwidth,
            top: _top,
            Thumbsize: _Thumbsize,
            left: _left,
            color: _color),
      ),
    );
  }

  void buildSetState(Offset localPosition, BuildContext context) {
    return setState(() {
      _left = localPosition.dx;
      _top = localPosition.dy;
      if (_left < 0) {
        _left = 0;
      } else if (0 <= _left && _left <= _colorwidth) {
        _left = _left;
        _hue = (360 * _left) / (_colorwidth);
      } else if (_left > _colorwidth) {
        _left = (_colorwidth);
        _hue = 360;
      }
      if (((5 / 360 - 5 / 360) < _left &&
              _left < (5 / 360 + 5 / 360) * _colorwidth) &&
          (_top < 5)) {
        _left = 5 / 360 * _colorwidth;
        _top = 0;
      } else if ((((5 + 350 / 6) / 360 - 5 / 360) * _colorwidth < _left &&
              _left < ((5 + 350 / 6) / 360 + 5 / 360) * _colorwidth) &&
          (_top < 5)) {
        _left = (5 + (1 * 350) / 6) / 360 * _colorwidth;
        _top = 0;
      } else if ((((5 + (2 * 350) / 6) / 360 - 5 / 360) * _colorwidth < _left &&
              _left < ((5 + (2 * 350) / 6) / 360 + 5 / 360) * _colorwidth) &&
          (_top < 5)) {
        _left = (5 + (2 * 350) / 6) / 360 * _colorwidth;
        _top = 0;
      } else if ((((5 + (3 * 350) / 6) / 360 - 5 / 360) * _colorwidth < _left &&
              _left < ((5 + (3 * 350) / 6) / 360 + 5 / 360) * _colorwidth) &&
          (_top < 5)) {
        _left = (5 + (3 * 350) / 6) / 360 * _colorwidth;
        _top = 0;
      } else if ((((5 + (4 * 350) / 6) / 360 - 5 / 360) * _colorwidth < _left &&
              _left < ((5 + (4 * 350) / 6) / 360 + 5 / 360) * _colorwidth) &&
          (_top < 5)) {
        _left = (5 + (4 * 350) / 6) / 360 * _colorwidth;
        _top = 0;
      } else if ((((5 + (5 * 350) / 6) / 360 - 5 / 360) * _colorwidth < _left &&
              _left < ((5 + (5 * 350) / 6) / 360 + 5 / 360) * _colorwidth) &&
          (_top < 5)) {
        _left = (5 + (5 * 350) / 6) / 360 * _colorwidth;
        _top = 0;
      } else if ((((5 + (6 * 350) / 6) / 360 - 5 / 360) * _colorwidth < _left &&
              _left < ((5 + (6 * 350) / 6) / 360 + 5 / 360)) &&
          (_top < 5)) {
        _left = (5 + (6 * 350) / 6) / 360 * _colorwidth;
        _top = 0;
      }
      if (_top <= 0) {
        _top = 0;
        _brightnum = 50;
        lightness = _brightnum / 100;
      } else if (0 <= _top && _top <= _colorHeight) {
        _brightnum = (100 * _top) / _colorHeight / 2 + 50;
        lightness = _brightnum / 100;
      } else if (_top > _colorHeight) {
        _top = _colorHeight;
        _brightnum = 100;
        lightness = _brightnum / 100;
      }
    });
  }
}

class ColorRect extends StatelessWidget {
  const ColorRect({
    Key key,
    @required double colorHeight,
    @required double colorwidth,
    @required double top,
    @required double Thumbsize,
    @required double left,
    @required Color color,
  })  : _colorHeight = colorHeight,
        _colorwidth = colorwidth,
        _top = top,
        _Thumbsize = Thumbsize,
        _left = left,
        _color = color,
        super(key: key);

  final double _colorHeight;
  final double _colorwidth;
  final double _top;
  final double _Thumbsize;
  final double _left;
  final Color _color;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: [
          Container(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: DecoratedBox(
                  child: Container(
                    height: _colorHeight,
                    width: _colorwidth,
                  ),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                      stops: [
                        0,
                        5 / 360,
                        (5 + 350 / 6) / 360,
                        (5 + (2 * 350) / 6) / 360,
                        (5 + (3 * 350) / 6) / 360,
                        (5 + (4 * 350) / 6) / 360,
                        (5 + (5 * 350) / 6) / 360,
                        (5 + (6 * 350) / 6) / 360,
                        1.0
                      ],
                      colors: [
                        Color.fromARGB(255, 255, 0, 0),
                        Color.fromARGB(255, 255, 0, 0),
                        Color.fromARGB(255, 255, 255, 0),
                        Color.fromARGB(255, 0, 255, 0),
                        Color.fromARGB(255, 0, 255, 255),
                        Color.fromARGB(255, 0, 0, 255),
                        Color.fromARGB(255, 255, 0, 255),
                        Color.fromARGB(255, 255, 0, 0),
                        Color.fromARGB(255, 255, 0, 0),
                      ],
                    ),
                  )),
            ),
          ),
          Container(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: DecoratedBox(
                  child: Container(
                    height: _colorHeight,
                    width: _colorwidth,
                  ),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Color.fromARGB(0, 255, 255, 255),
                        Colors.white,
                      ],
                    ),
                  )),
            ),
          ),
          Container(
              child: Thumb(
                  top: _top,
                  Thumbsize: _Thumbsize,
                  left: _left,
                  color: _color)),
        ],
      ),
    );
  }
}

class Thumb extends StatelessWidget {
  const Thumb({
    Key key,
    @required double top,
    @required double Thumbsize,
    @required double left,
    @required Color color,
  })  : _top = top,
        _Thumbsize = Thumbsize,
        _left = left,
        _color = color,
        super(key: key);

  final double _top;
  final double _Thumbsize;
  final double _left;
  final Color _color;

  @override
  Widget build(BuildContext context) {
    return Positioned(
        top: _top - _Thumbsize / 2,
        left: _left - _Thumbsize / 2,
        child: GestureDetector(
            child: Container(
          child: Icon(
            Icons.circle,
            color: _color,
            size: _Thumbsize,
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                blurRadius: 0.1, //阴影范围
                spreadRadius: 0.001, //阴影浓度
                color: Colors.black, //阴影颜色
              ),
            ],
          ),
        )));
  }
}

下面是使用方法。

RectangleColorPicker(
   [initialColor: Colors.white,
   colorWidth: 360,
   colorHeight: 150,
   onTapUpListener: (_color) { }
   colorListener: (_color) { }
   ]
),

具体效果图:

总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了两种颜色选色板的使用,后面还会陆续发布一些flutter的组件使用教程。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

时间: 2021-10-11

Flutter自定义圆盘取色器

本文实例为大家分享了Flutter自定义圆盘取色器的具体代码,供大家参考,具体内容如下 下面展示一些 内联代码片. 圆盘取色器 效果图 完整代码 import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class CircularColorFinder extends Sta

PHP模板引擎Smarty自定义变量调解器用法

本文实例讲述了PHP模板引擎Smarty自定义变量调解器用法.分享给大家供大家参考,具体如下: 在 PHP 中,有很多处理文本的函数,您可以把要处理的文本通过函数处理之后,再调用 Smarty 模板引擎中的 assign() 赋值给变量,分配到模板中进行显示. Smarty 中的变量调解器和 PHP 中处理文本的函数相似,不过语法不相同,在 Smarty 中,是通过 "|" 后面直接跟调解器函数名,如果有参数,得加在 ":" 后面,多个参数的话,累加即可. 格式:{

javascript编程开发中取色器及封装$函数用法示例

本文实例讲述了javascript编程开发中取色器及封装$函数用法.分享给大家供大家参考,具体如下: 1.封装$函数 function $(str){ //如果传入的是'#' 则选择id标签 //如果传入的是'.' 则选择所有的类名标签 //如果传入的既不是'#也不是'.' 选择复合标签 //判断传入的值 if(typeof str !='string'){ console.log('传入的参数有误!'); return null; } //获取参数的第一个字母 var firstChar=st

JS实现的RGB网页颜色在线取色器完整实例

本文实例讲述了JS实现的RGB网页颜色在线取色器.分享给大家供大家参考,具体如下: 运行效果图如下: 完整实例代码如下: <html> <head> <meta content="text/html; charset=utf-8" http-equiv="content-type"> <meta name="description" content="在线取色器"> <me

在C#使用字典存储事件示例及实现自定义事件访问器

使用字典存储事件实例 accessor-declarations 的一种用法是公开很多事件但不为每个事件分配字段,而是使用字典来存储这些事件实例.这只在具有很多事件但您预计大多数事件都不会实现时才有用. public delegate void EventHandler1(int i); public delegate void EventHandler2(string s); public class PropertyEventsSample { private System.Collecti

Yii2实现自定义独立验证器的方法

本文实例讲述了Yii2实现自定义独立验证器的方法.分享给大家供大家参考,具体如下: 新建一个文件: <?php /** * author : forecho <caizhenghai@gmail.com> * createTime : 2015/7/1 14:54 * description: */ namespace common\helps; use yii\validators\Validator; class ArrayValidator extends Validator {

spring security自定义决策管理器

首先介绍下Spring的决策管理器,其接口为AccessDecisionManager,抽象类为AbstractAccessDecisionManager.而我们要自定义决策管理器的话一般是继承抽象类而不去直接实现接口. 在Spring中引入了投票器(AccessDecisionVoter)的概念,有无权限访问的最终觉得权是由投票器来决定的,最常见的投票器为RoleVoter,在RoleVoter中定义了权限的前缀,先看下Spring在RoleVoter中是怎么处理授权的. public int

Django框架自定义模型管理器与元选项用法分析

本文实例讲述了Django框架自定义模型管理器与元选项用法.分享给大家供大家参考,具体如下: 自定义模型管理器 每个模型类默认都有一个 objects 类属性,可以把它叫 模型管理器.它由django自动生成,类型为 django.db.models.manager.Manager 可以在模型类中自定义模型管理器,自定义后, Django将不再生成默认的 objects.(模型类可以自定义多个管理器) 例如: class Department(models.Model): # 自定义模型管理器

Django中自定义模型管理器(Manager)及方法

1.自定义管理器(Manager) 在语句Book.objects.all()中, objects 是一个特殊的属性,通过它来查询数据库,它就是模型的一个Manager. 每个Django模型至少有一个manager,你可以创建自定义manager以定制数据库的访问. 这里有两个方法创建自定义manager:添加额外的manager;修改manager返回的初始Queryset. 添加额外的manager 增加额外的manager是为模块添加 表级功能 的首选办法.(至于 行级功能 ,也就是只作

Spring自定义参数解析器代码实例

这篇文章主要介绍了Spring自定义参数解析器代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 结合redis编写User自定义参数解析器UserArgumentResolver import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation

flutter 自定义card阴影效果及card使用

最近在用flutter写web程序,简直是炼狱模式..然后遇到个需求,原本的Card阴影无法满足产品需求,需要像IOS 那种超级高大上的,似影非影的效果..(简直分分钟想打死产品) 一开始,当然都是百度了,于是百度到了一个方法:BoxShadow! 于是高高兴兴开干了,代码如下 嗯...看上去好像没啥毛病,Y轴方向偏移7,blurRadius:模糊延申14,spreadRadius:不模糊的不要延申,为0 跑到安卓的浏览器上 简直Perfect!!!完工交差...(just我以为) 看到测试淫笑