每日见闻之Container Decoration

1 Decoation 主要有两个方法

javascript 复制代码
Path getClipPath(Rect rect, TextDirection textDirection) {
  throw UnsupportedError('${objectRuntimeType(this, 'This Decoration subclass')} does not expect to be used for clipping.');
}
less 复制代码
@factory
BoxPainter createBoxPainter([ VoidCallback onChanged ]);

getClipPath 返回的是裁剪的路径,裁剪的是child的显示区域。Rect 就是Container的范围。

createBoxPainter 返回的是自定义绘制内容的BoxPointer

2 BoxPainter主要是实现下面的方法

arduino 复制代码
void paint(Canvas canvas, Offset offset, ImageConfiguration configuration);

offset Container 在父节点中的位置

configuration Container的一些信息,包含宽高

最后留下一个demo,裁剪圆形图片

scala 复制代码
// 自定义装饰:绘制矩形,但裁剪为圆形
class CircleWithRectDecoration extends Decoration {
  final Color color;

  const CircleWithRectDecoration({required this.color});

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _CircleWithRectPainter(this, onChanged);
  }

  @override
  Path getClipPath(Rect rect, TextDirection textDirection) {
    // 返回圆形裁剪路径
    return Path()
      ..addRect(Rect.fromCenter(center: rect.center, width: rect.width / 2, height: rect.height/2));
  }
}

class _CircleWithRectPainter extends BoxPainter {
  final CircleWithRectDecoration decoration;

  _CircleWithRectPainter(this.decoration, VoidCallback? onChanged) : super(onChanged);

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    final rect = offset & configuration.size!;
    final paint = Paint()
      ..color = decoration.color
      ..style = PaintingStyle.fill;

    // 绘制矩形(而非圆形)
    canvas.drawOval(rect, paint);
  }
}

使用

less 复制代码
Container(
  width: 150,
  height: 150,
  clipBehavior: Clip.antiAlias, // 启用裁剪
  decoration: const CircleWithRectDecoration(color: Colors.blue),
  // 默认 clipBehavior: Clip.none,getClipPath() 无效
  child: const FlutterLogo(size: 150),
)
相关推荐
FungLeo13 小时前
FengCMS · PHP+MySQL 升级实录 · 危险默认值之殇:root/123456、认证码 8888 写进配置加载器
android·mysql·php·安全加固·fengcms
yz_aiks13 小时前
Termux 使用教程:把安卓手机变成随身 Linux(装 Python、SSH 远程、跑自动化脚本)
android·linux·python·智能手机·ssh·termux
booboosui21 小时前
编号没变,消息还是来了:Mac 端通知读取漏第二条的原因
android
雨白2 天前
单例设计模式:从 Java/Kotlin 实现到 Android 实战
android
hai_android2 天前
一行 asLiveData,背后是一座生命周期的桥
android·java·kotlin
阿杰m2 天前
Android源码第二十三章:Telephony、RIL 与 IMS——来电怎么到应用?
android
booboosui2 天前
没人认领 .md:安卓把报告交给了音乐播放器打开
android
用户60709759149062 天前
AOSP 14 OTA 升级指导(四):update_engine 内部机制——Action 流水线与写盘
android
恋猫de小郭2 天前
Jetpack Compose 1.13 发布,憋了这么久终有交代了
android·前端·flutter
JMchen1232 天前
【Android 性能优化实战 60 讲】12 异步 Inflate 实战与痛击:源码拆解原生瓶颈,手写增强版布局预加载框架
android·性能优化·实战·启动优化·异步inflate·x2c