Created
March 7, 2022 07:17
-
-
Save abhaysood/9e40403eb87d3713a1f3a20ed895b547 to your computer and use it in GitHub Desktop.
Drawing a inner shadow using custom paint along a path
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 'package:flutter/material.dart'; | |
void main() => runApp(const MyApp()); | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
static const String _title = 'Flutter Code Sample'; | |
@override | |
Widget build(BuildContext context) { | |
const bgColor = Color.fromARGB(255, 249, 250, 251); | |
return MaterialApp( | |
title: _title, | |
home: Scaffold( | |
backgroundColor: bgColor, | |
body: Center( | |
child: SizedBox( | |
height: 200, | |
width: 200, | |
child: CustomPaint( | |
painter: MyCustomPainter( | |
backgroundColor: bgColor, | |
), | |
), | |
), | |
), | |
), | |
); | |
} | |
} | |
class MyCustomPainter extends CustomPainter { | |
MyCustomPainter({ | |
required this.backgroundColor, | |
}) : shadow = Shadow( | |
color: Colors.black38, | |
offset: Offset(0, 2), | |
blurRadius: 4, | |
); | |
final Color backgroundColor; | |
final Shadow shadow; | |
@override | |
void paint(Canvas canvas, Size size) { | |
canvas.save(); | |
final path = Path() | |
..lineTo(0.0, size.height - 50.0) | |
..lineTo(size.width, size.height) | |
..lineTo(size.width, 0.0) | |
..close(); | |
canvas.clipPath(path); | |
canvas.saveLayer(Offset.zero & size, Paint()); | |
final outerRectPaint = Paint() | |
..color = Color.alphaBlend(shadow.color, backgroundColor); | |
final innerRectPaint = Paint() | |
..color = shadow.color | |
..maskFilter = MaskFilter.blur(BlurStyle.normal, shadow.blurRadius / 2) | |
..blendMode = BlendMode.srcOut; | |
canvas.drawPath(path, outerRectPaint); | |
canvas.drawPath(path, innerRectPaint); | |
canvas | |
..restore() | |
..restore(); | |
} | |
@override | |
bool shouldRepaint(covariant CustomPainter oldDelegate) { | |
return false; | |
} | |
} | |
class DiagonalPathClipper extends CustomClipper<Path> { | |
const DiagonalPathClipper(); | |
@override | |
Path getClip(Size size) { | |
final path = Path() | |
..lineTo(0.0, size.height - 50.0) | |
..lineTo(size.width, size.height) | |
..lineTo(size.width, 0.0) | |
..close(); | |
return path; | |
} | |
@override | |
bool shouldReclip(CustomClipper<Path> oldClipper) { | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment