Skip to content

Instantly share code, notes, and snippets.

@talamaska
Forked from av/main.dart
Created February 1, 2021 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save talamaska/30668f2b51c17468e11f5e958262bc09 to your computer and use it in GitHub Desktop.
Save talamaska/30668f2b51c17468e11f5e958262bc09 to your computer and use it in GitHub Desktop.
Flutter: texture generator playground
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
void main() async => runApp(MaterialApp(home: Root()));
/// Waits till [ui.Image] is generated and renders
/// it using [CustomPaint] to render it. Allows use of [MediaQuery]
class Root extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder<ui.Image>(
future: generateImage(MediaQuery.of(context).size),
builder: (context, snapshot) {
if (snapshot.hasData) {
return CustomPaint(
// Passing our image
painter: ImagePainter(image: snapshot.data),
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
),
);
}
return Text('Generating image...');
},
);
}
}
/// Paints given [ui.Image] on [ui.Canvas]
/// does not repaint
class ImagePainter extends CustomPainter {
ui.Image image;
ImagePainter({this.image});
@override
void paint(Canvas canvas, Size size) {
canvas.drawImage(image, Offset.zero, Paint());
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
/// Generates a [ui.Image] with certain pixel data
Future<ui.Image> generateImage(Size size) async {
int width = size.width.ceil();
int height = size.height.ceil();
var completer = Completer<ui.Image>();
Int32List pixels = Int32List(width * height);
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
int index = y * width + x;
pixels[index] = generatePixel(x, y, size);
}
}
ui.decodeImageFromPixels(
pixels.buffer.asUint8List(),
width,
height,
ui.PixelFormat.bgra8888,
(ui.Image img) {
completer.complete(img);
},
);
return completer.future;
}
/// Main area of interest, this function will
/// return color for each particular color on our [ui.Image]
int generatePixel(int x, int y, Size size) {
return Color.fromRGBO(x, 0, y, 1.0).value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment