Certainly! Below is a Flutter class called MaskPage that meets your requirements. This class creates a 300x400 bordered canvas where you can draw, toggles between black and white drawing colors, and has a black background with transparent black pixels in the user interface.
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
class MaskPage extends StatefulWidget {
@override
_MaskPageState createState() => _MaskPageState();
}
class _MaskPageState extends State<MaskPage> {
Color _drawColor = Colors.white; // Start with white color
List<Offset?> _points = []; // Store points for drawing
void _toggleColor() {
setState(() {
_drawColor = _drawColor == Colors.white ? Colors.black : Colors.white;
});
}
void _addPoint(Offset point) {
setState(() {
_points.add(point);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Mask Page'),
actions: [
IconButton(
icon: Icon(Icons.color_lens),
onPressed: _toggleColor,
),
],
),
body: Center(
child: Container(
width: 300,
height: 400,
decoration: BoxDecoration(
border: Border.all(color: Colors.white),
color: Colors.black,
),
child: GestureDetector(
onPanUpdate: (details) {
RenderBox renderBox = context.findRenderObject() as RenderBox;
Offset localPosition = renderBox.globalToLocal(details.globalPosition);
if (localPosition.dx >= 0 && localPosition.dx <= 300 &&
localPosition.dy >= 0 && localPosition.dy <= 400) {
_addPoint(localPosition);
}
},
onPanEnd: (details) {
_points.add(null); // Add a null point to indicate the end of a stroke
},
child: CustomPaint(
painter: MaskPainter(points: _points, drawColor: _drawColor),
),
),
),
),
);
}
}
class MaskPainter extends CustomPainter {
final List<Offset?> points;
final Color drawColor;
MaskPainter({required this.points, required this.drawColor});
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..color = drawColor
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;
for (int i = 0; i < points.length - 1; i++) {
if (points[i] != null && points[i + 1] != null) {
canvas.drawLine(points[i]!, points[i + 1]!, paint);
}
}
}
@override
bool shouldRepaint(MaskPainter oldDelegate) {
return oldDelegate.points != points || oldDelegate.drawColor != drawColor;
}
}
void main() {
runApp(MaterialApp(
home: MaskPage(),
));
}
Explanation:
- Canvas Setup: The
MaskPage class creates a Container with a fixed size of 300x400 pixels and a white border. The background color is set to black.
- Drawing Logic: The
GestureDetector captures touch events to allow drawing on the canvas. The points are stored in a list, and the CustomPainter is used to draw lines between these points.
- Color Toggle: An
IconButton in the app bar toggles the drawing color between black and white.
- Transparent Pixels: The drawing logic uses white for drawing, which will appear transparent against the black background.
You can run this code in a Flutter environment to see the drawing functionality in action.