見出し画像

Flutterログ #4 写真を選んで加工して表示する

写真を選ぶのは、image_pickerというプラグインを使うだけで簡単にできる。

Exampleの言う通り実装して、colorBlendModeを試してみたかったので使っってみた。そもそもカラーブレンドって何?という方はこちら。ぼくも何度か勉強したけど忘れる・・・

Photoshopだと画像×画像で合成したりもできるのですが、Flutterは画像×色(RGBA)でしかできないようです。

先にpubspec.yamlにimage_pickerを追加してから `flutter packages get` を実行。(vscode上でもできる)

$ git diff pubspec.yaml 
diff --git a/pubspec.yaml b/pubspec.yaml
index 275fd3c..150b40a 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -5,6 +5,8 @@ dependencies:
   flutter:
     sdk: flutter
 
+  image_picker: ^0.4.5 
+
   # The following adds the Cupertino Icons font to your application.
   # Use with the CupertinoIcons class for iOS style icons.
   cupertino_icons: ^0.1.0

パッケージの使い方はこれ読む。

その後いろいろ試してみたら、最終的にこんな感じになった。

import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Test'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  File _image;

  Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);

    setState(() {
      _image = image;
    });
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> widgets = new List();
    widgets.add(new Text('selected image (original):'));
    widgets.add(
      _image == null
          ? new Text("No image selected")
          : new Image.file(
              _image,
            ),
    );

    for (BlendMode mode in BlendMode.values) {
      widgets.add(new Text("selected image (${mode} blended):"));
      widgets.add(
        _image == null
            ? new Text("No image selected")
            : new Image.file(
                _image,
                color: const Color(0xFF00FFFF),
                colorBlendMode: mode,
              ),
      );
    }
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new ListView(
          children: widgets,
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: getImage,
        tooltip: "Pick Image",
        child: new Icon(Icons.add_a_photo),
      ),
    );
  }
}

セピア色(#00FFFF)とカラーブレンドしてみた。スクショ例はこんなかんじ。(iPhoneシミュレーターで動作確認)


この記事が気に入ったらサポートをしてみませんか?