texture (image) on text in flutter

1,616

the operation of drawing image on text is asynchronous, because it waits for the image to be loaded and set it on the TextStyle's foreground shader.

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;

String textureName = "images/texture.jpg";
 Future<TextStyle> textureText(TextStyle textStyle,
    ) async {
  ui.Image img;
  img = await ImageLoader.load(textureName);
  Float64List matrix4 = new Matrix4.identity().storage;
  return textStyle.copyWith(
      foreground: Paint1()
        ..shader = ImageShader(img, TileMode.mirror, TileMode.mirror, matrix4));
}

below, FutureBuilder calls textureText and use the returned TextStyle

  Widget tt = new FutureBuilder<TextStyle>(
    future: texturedText(
        TextStyle(fontSize: 70.0,), // a Future<String> or null
    builder: (BuildContext context, AsyncSnapshot<TextStyle> snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.waiting:
          return new Text('Awaiting result...');
        default:
          if (snapshot.hasError)
            return new Text('Error: ${snapshot.error}');
          else
            return new Text(
              'TEXTURE',
              style: snapshot.data,
            );
      }
    },
  );

you can use tt (texturedText) like a normal widget.

A complete example is also available in this repo.

Share:
1,616
AbdulMomen عبدالمؤمن
Author by

AbdulMomen عبدالمؤمن

Hello there! ;) I like computers, mathematics, philosophy, logic, music and religion.

Updated on December 07, 2022

Comments

  • AbdulMomen عبدالمؤمن
    AbdulMomen عبدالمؤمن over 1 year

    is there a way to put image (texture) on a text in Flutter?

    like the image shown below

    enter image description here