📷
Flutterで画像をバックグラウンドに表示する
環境
- macOS Big Sur Version 11.3.1
- Flutter 2.2.0
- Dart 2.13.0
画像をバックグラウンドに表示する
画像を置くフォルダを用意
まず、利用したい画像を用意してプロジェクト内のフォルダに入れます。
※ネット上にある画像を使うパターンもできますが、今回はあらかじめ用意した画像を読み込む形にします。
単純にこちらのサンプルのほうが少ないなーという主観的観測結果によるものです😎
プロジェクト直下にimagesフォルダをつくります。(フォルダの名前は任意です。)
androidでエラーになってますが気にしないでいただければ・・・w
次に作成したフォルダにぱくたそ様から拾ってきたいい感じフリー画像を置きます。
ファイル名はbackground-sample.jpgとしました。
pubspec.yamlに設定を追加する
Flutterでプロジェクト内に用意した画像を利用するには、pubspec.yamlに設定が必要になります。
以下のようにpubspec.yamlのflutterキー配下にあるassetsに上で作成したフォルダ名を追記します。
BoxDecorationを使って画像をバックグラウンドに表示する
単に画像を読み込むだけならImageウィジェットを使えば事足りますが、背景画像として使いたい場合にはBoxDecorationとDecorationImageを使います。
ポイントをまとめると、
-
ContainerのdecorationプロパティにBoxDecorationを指定する -
BoxDecorationのimageプロパティにDecorationImageを指定する -
DecorationImageのimageプロパティに画像を表示するウィジェットを利用してパスを指定する
import 'package:flutter/material.dart';
class BackGroundImage extends StatelessWidget {
const BackGroundImage({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('画像をバックグラウンドに設定サンプル'),
),
body: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('images/background-sample.jpg'),
fit: BoxFit.cover,
)),
child: const Center(
child: Text(
'ホラーゲームとかに使えそう',
style: TextStyle(
color: Colors.white,
fontSize: 30,
),
),
),
),
);
}
}
ソース全体




Discussion