flutter 使用SVG作为容器的背景图像

tnkciper  于 2023-05-01  发布在  Flutter
关注(0)|答案(4)|浏览(121)

this question开始,我使用Flutter的SVG包(flutter_svg)来渲染SVG image
我想使用SVG作为Container背景,中间是Text

这是我到目前为止的代码:

Container(
      decoration: BoxDecoration(
          image: DecorationImage(image: SvgPicture.asset(
            'assets/example.svg',
          ),),
      ),
      children: <Widget>[
        Text('Welcome to my Flutter App',
          style: Theme.of(context).textTheme.display1.copyWith(
            color: Colors.white,
            fontWeight: FontWeight.bold
          )
        ),
      ],
    )

我发现的问题是SvgPicture不是ImageProvider,所以我不能添加BoxDecoration来获得背景图像。
有没有办法使用SvgPicture作为Container的框装饰或背景?

nom7f22z

nom7f22z1#

使用SvgPicture的确切方法是这样的:

Widget build(BuildContext context) {

  return Scaffold(
    body: Stack(
      children: <Widget>[
        SvgPicture.asset(
          'assets/images/splash/background.svg',
          alignment: Alignment.center,
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
        ),
        Container(
          child: Column(
            children: <Widget>[Expanded(child: _createLogo())],
          ),
        ),
      ],
    ),
  );
}
waxmsbnn

waxmsbnn2#

使用stack()并在其上构建所有内容如何?这就是我如何做到这一点,只是一个图像作为背景的完整视口。

e1xvtsh3

e1xvtsh33#

也可以使用flutter_svg_provider
就像这样:

import 'package:flutter_svg_provider/flutter_svg_provider.dart';

Container(
      decoration: BoxDecoration(
          image: DecorationImage(image: Svg(
            'assets/example.svg',
          ),),
      ),
    )
1qczuiv0

1qczuiv04#

这对我很有效

import 'dart:ui' as ui;

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

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: _getSvgImageProvider('assets/background.svg'),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
        child: Text('Hello World'),
      ),
    );
  }

  ImageProvider _getSvgImageProvider(String assetName) {
    final svgString = DefaultAssetBundle.of(context).loadString(assetName);
    final DrawableRoot svgDrawableRoot = SvgParser.parse(svgString);
    final ui.Picture picture = svgDrawableRoot.toPicture();
    final ui.Image image = picture.toImage(
      svgDrawableRoot.viewport.viewBox.width.toInt(),
      svgDrawableRoot.viewport.viewBox.height.toInt(),
    );
    final provider = MemoryImage(
      Uint8List.view(image.toByteData(format: ui.ImageByteFormat.png).buffer),
    );
    return provider;
  }
}

相关问题