Last active
July 17, 2024 21:26
-
-
Save av/42724afc37de2ae412a67561ae8b011c to your computer and use it in GitHub Desktop.
Flutter: texture generator playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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