Created
June 15, 2019 15:26
-
-
Save slightfoot/a1ef4088f55619bea35f0348923a4764 to your computer and use it in GitHub Desktop.
Example of how to add a vignette style border to any widget using a CustomPainter and magical BlendMode's.
This file contains hidden or 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 'package:flutter/material.dart'; | |
void main() => runApp(PhotoTestApp()); | |
class PhotoTestApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Container( | |
color: Colors.red, | |
child: Center( | |
child: PhotoBorder.basic( | |
amount: 30.0, | |
child: Image.asset('assets/image.jpg'), | |
), | |
), | |
), | |
); | |
} | |
} | |
class PhotoBorder extends StatelessWidget { | |
const PhotoBorder.basic({ | |
Key key, | |
double amount, | |
this.child, | |
}) : this.borderDepth = amount * 2, | |
this.borderBlur = amount, | |
super(key: key); | |
const PhotoBorder({ | |
Key key, | |
@required this.borderDepth, | |
@required this.borderBlur, | |
this.child, | |
}) : super(key: key); | |
final double borderDepth; | |
final double borderBlur; | |
final Widget child; | |
@override | |
Widget build(BuildContext context) { | |
return CustomPaint( | |
foregroundPainter: _PhotoBorderPainter(this), | |
child: child, | |
); | |
} | |
} | |
class _PhotoBorderPainter extends CustomPainter { | |
const _PhotoBorderPainter(this.widget); | |
final PhotoBorder widget; | |
@override | |
void paint(Canvas canvas, Size size) { | |
final rect = (Offset.zero & size).deflate(widget.borderDepth); | |
canvas.saveLayer((Offset.zero & size), Paint()..blendMode = BlendMode.dstATop); | |
canvas.drawRect( | |
rect, | |
Paint()..maskFilter = MaskFilter.blur(BlurStyle.normal, widget.borderBlur), | |
); | |
canvas.restore(); | |
} | |
@override | |
bool shouldRepaint(_PhotoBorderPainter old) { | |
return old.widget.borderBlur != widget.borderBlur || old.widget.borderDepth != widget.borderDepth; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment