Line data Source code
1 : import 'dart:ui'; 2 : 3 : import '../../../components.dart'; 4 : import '../../palette.dart'; 5 : 6 : /// Adds a collection of paints to a component 7 : /// 8 : /// Component will always have a main Paint that can be accessed 9 : /// by the [paint] attribute and other paints can be manipulated/accessed 10 : /// using [getPaint], [setPaint] and [deletePaint] by a paintId of generic type [T], that can be omited if the component only have one paint. 11 : mixin HasPaint<T extends Object> on BaseComponent { 12 : final Map<T, Paint> _paints = {}; 13 : 14 : Paint paint = BasicPalette.white.paint(); 15 : 16 2 : void _asserGenerics() { 17 : assert( 18 3 : T != Object, 19 : 'When using the paint collection, component should declare a generic type', 20 : ); 21 : } 22 : 23 : /// Gets a paint from the collection. 24 : /// 25 : /// Returns the main paint if no [paintId] is provided. 26 3 : Paint getPaint([T? paintId]) { 27 : if (paintId == null) { 28 2 : return paint; 29 : } 30 : 31 2 : _asserGenerics(); 32 2 : final _paint = _paints[paintId]; 33 : 34 : if (_paint == null) { 35 2 : throw ArgumentError('No Paint found for $paintId'); 36 : } 37 : 38 : return _paint; 39 : } 40 : 41 : /// Sets a paint on the collection 42 2 : void setPaint(T paintId, Paint paint) { 43 2 : _asserGenerics(); 44 2 : _paints[paintId] = paint; 45 : } 46 : 47 : /// Removes a paint from the collection 48 2 : void deletePaint(T paintId) { 49 2 : _asserGenerics(); 50 2 : _paints.remove(paintId); 51 : } 52 : 53 : /// Manipulate the paint to make it fully transparent 54 2 : void makeTransparent({T? paintId}) { 55 2 : setOpacity(0, paintId: paintId); 56 : } 57 : 58 : /// Manipulate the paint to make it fully opaque 59 2 : void makeOpaque({T? paintId}) { 60 2 : setOpacity(1, paintId: paintId); 61 : } 62 : 63 : /// Changes the opacity of the paint 64 3 : void setOpacity(double opacity, {T? paintId}) { 65 6 : if (opacity < 0 || opacity > 1) { 66 1 : throw ArgumentError('Opacity needs to be between 0 and 1'); 67 : } 68 : 69 15 : getPaint(paintId).color = paint.color.withOpacity(opacity); 70 : } 71 : 72 : /// Returns the current opacity 73 0 : double getOpacity({T? paintId}) { 74 0 : return getPaint(paintId).color.opacity; 75 : } 76 : 77 : /// Shortcut for changing the color of the paint 78 2 : void setColor(Color color, {T? paintId}) { 79 4 : getPaint(paintId).color = color; 80 : } 81 : 82 : /// Applies a color filter to the paint which will make 83 : /// things rendered with the paint looking like it was 84 : // tinted with the given color 85 3 : void tint(Color color, {T? paintId}) { 86 9 : getPaint(paintId).colorFilter = ColorFilter.mode(color, BlendMode.multiply); 87 : } 88 : }