You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何为Container设置此类纹理?是否可行?

Flutter Container 添加斜纹纹理(非图片方案)

当然可行,以下是两种无需图片的实现方案,适合新手参考:

方案1:利用 BoxDecoration + LinearGradient 快速实现

这种方法代码量少,上手简单,通过重复渐变模拟纹理:

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

// 使用示例
Container(
  width: 300,
  height: 200,
  decoration: BoxDecoration(
    color: Colors.white, // 容器底色
    backgroundBlendMode: BlendMode.multiply,
    gradient: LinearGradient(
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
      colors: [
        Colors.transparent,
        Colors.grey.shade200, // 条纹颜色
        Colors.transparent,
      ],
      stops: const [0.0, 0.5, 1.0], // 控制条纹宽度
      tileMode: TileMode.repeated, // 重复渐变形成纹理
      transform: const GradientRotation(pi / 4), // 旋转45度变成斜纹
    ),
  ),
  child: const Center(child: Text('带斜纹纹理的容器')),
)

调整colors、stops和GradientRotation的角度,就能匹配你需要的纹理样式。

方案2:自定义 CustomPainter 实现精确控制

如果需要更精准的条纹粗细、间距,用自定义绘制的方式更灵活:

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

class DiagonalTexturePainter extends CustomPainter {
  final Color lineColor;
  final double lineWidth;
  final double spacing;

  DiagonalTexturePainter({
    this.lineColor = const Color(0xFFEEEEEE),
    this.lineWidth = 1.0,
    this.spacing = 10.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = lineColor
      ..strokeWidth = lineWidth;

    final diagonalLength = sqrt(size.width * size.width + size.height * size.height);
    final lineCount = (diagonalLength / spacing).ceil();

    // 绘制重复斜线条
    for (int i = -lineCount; i < lineCount; i++) {
      final startOffset = Offset(i * spacing, 0);
      final endOffset = Offset(i * spacing + size.height, size.height);
      canvas.drawLine(startOffset, endOffset, paint);
    }
  }

  @override
  bool shouldRepaint(covariant DiagonalTexturePainter oldDelegate) {
    return oldDelegate.lineColor != lineColor ||
        oldDelegate.lineWidth != lineWidth ||
        oldDelegate.spacing != spacing;
  }
}

// 使用示例
Container(
  width: 300,
  height: 200,
  child: CustomPaint(
    painter: DiagonalTexturePainter(
      lineColor: Colors.grey.shade200,
      lineWidth: 1.5,
      spacing: 12.0,
    ),
    child: const Center(child: Text('自定义纹理容器')),
  ),
)

通过修改lineWidth(线条粗细)和spacing(线条间距),可以完全复刻你需要的纹理效果。

内容的提问来源于stack exchange,提问作者Manisha Chaudhari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 17:45:17