实现效果
在提供设计代码前,我还是习惯性地先将设计的效果图放入以便大家能快速参考是否是自己想要的,本文主要内容为便签内部的输入框和后面便签下划线效果的蒙版的设计和实现。
线条背景View
整体层次上主要采用Stack作为层叠结构,线条是我用Canvas进行绘制的,View的核心内容如下:
必填:
- height:整个背景高度
- width:线长
- separateheight:每个相隔高度(一般是字符大小,如果字符有设行间距就是fontsize*height)
可选:
- color:分割线颜色(默认灰)
- firstheight:第一行调整高度,不然可能离文字过近(默认5)
- twospace:两边间隔
View代码
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class TextLineView extends CustomPainter{
Paint linePaint=Paint();
// late Color linecolor;
late double height;
late double separateheigh;
late double width;
double firstheight=5;
double twospace=5;
/**
* height:整个背景高度
* width:线长
* separateheight:每个相隔高度(一般是字符大小,如果字符有设行间距就是fontsize*height)
* color:分割线颜色(默认灰)
* firstheight:第一行调整高度,不然可能离文字过近(默认5)
* twospace:两边间隔
*/
TextLineView(double height,double width,double separateheight,{Color ? color=Colors.grey,double ? firstheight,double ? twospace}){
//this.linecolor=color;
this.height=height;
this.width=width;
this.separateheigh=separateheight;
if(color!=null){
linePaint..color=color;
}
if(firstheight!=null){
this.firstheight=firstheight;
}
if(twospace!=null){
this.twospace=twospace;
}
}
@override
void paint(Canvas canvas, Size size) {
int counts=height~/separateheigh;
for(int i=1;i<counts;i++){
canvas.drawLine(Offset(5,separateheigh*i+firstheight), Offset(width-5,separateheigh*i+firstheight), linePaint);
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
return false;
}
}
实际调用
如效果图所示的实际调用如下,你可以直接在某个Widget的child或children里添加,
Scaffold(
backgroundColor: Colors.white,
resizeToAvoidBottomInset: false,
body: Container(
height: SizeConfig.getpercentHeight(context, 60) - 60,//高度计算
child: Stack(
children: [
TextField(
maxLength: 300,
textAlign: TextAlign.start,
maxLines: 15,
cursorColor: Colors.grey,
style: TextStyle(
color: Colors.black,
fontSize: 15,
height: 1.5,
wordSpacing: 2,
),
decoration: InputDecoration(
hintText: "please write down your thoughts",
hintStyle: TextStyle(
color: Colors.black26, fontSize: 15),
border: InputBorder.none,
isCollapsed: true,
contentPadding: EdgeInsets.all(5.0),
enabledBorder: null,
disabledBorder: null),
),//输入框样式
CustomPaint(
painter: TextLineView(
SizeConfig.getpercentHeight(context, 60) -
80,//这里多减去一部分是因为不想画到统计字数那边
SizeConfig.getpercentwidth(context, 80) -
20,
22.5),
),//便签背景
],
),
),
)
其中SizeConfig是一个计算屏幕百分比的一个工具类
import 'package:flutter/widgets.dart';
class SizeConfig {
//获取宽度比例
static double getpercentwidth(BuildContext context,int width) {
return MediaQuery.of(context).size.width*width / 100;
}
//获取高度比例
static double getpercentHeight(BuildContext context,int height) {
return MediaQuery.of(context).size.height*height / 100;
}
//获取比例相减值
static double compare(BuildContext context,int value1,int value2) {
return MediaQuery.of(context).size.height*(value2-value1) / 100;
}
}