Created
October 9, 2020 10:31
-
-
Save sna2021/de2261563dd202815a6cfb0a49cb20dc to your computer and use it in GitHub Desktop.
CustomClipper
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(MaterialApp( | |
home: ClipSamplePage(), | |
)); | |
class ClipSamplePage extends StatefulWidget { | |
@override | |
_ClipSamplePageState createState() => _ClipSamplePageState(); | |
} | |
class _ClipSamplePageState extends State<ClipSamplePage> { | |
final CustomClipper<Rect> clipper1 = CircleClipper(ReclipType.fromHeight); | |
final CustomClipper<Rect> clipper2 = CircleClipper(ReclipType.fromWidth); | |
CustomClipper<Rect> currentClipper; | |
@override | |
void initState() { | |
currentClipper = clipper1; | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return GestureDetector( | |
onTap: _update, | |
child: Container( | |
alignment: Alignment.center, | |
padding: const EdgeInsets.all(16), | |
child: ClipOval( | |
clipper: currentClipper, | |
child: Image.network( | |
"https://naekvatoremsk.ru/sites/default/files/2_1718.jpg", | |
), | |
), | |
), | |
); | |
} | |
// При нажатии на картинку меняем наш currentClipper | |
void _update() { | |
setState(() { | |
if (currentClipper == clipper1){ | |
currentClipper = clipper2; | |
} else { | |
currentClipper = clipper1; | |
} | |
}); | |
} | |
} | |
// Определяет как расчитывать диаметр, исходя из ширины или высоты | |
enum ReclipType { fromHeight, fromWidth } | |
class CircleClipper extends CustomClipper<Rect> { | |
const CircleClipper(this.reclipType); | |
final ReclipType reclipType; | |
// Расскоментируйте разные варианты, что бы увидеть разницу | |
// 1 - Вариант когда clipper не будет обрезать, даже если мы передали другой clipper | |
@override | |
bool shouldReclip(CircleClipper oldClipper) => false; | |
// 2 - Вариант когда clipper будет всегда отрабатывать | |
// bool shouldReclip(CircleClipper oldClipper) => true; | |
// 3 - Вариант когда clipper отработает, если тип не совпадает с предыдущим | |
// bool shouldReclip(CircleClipper oldClipper) => oldClipper.reclipType != reclipType; | |
@override | |
Rect getClip(Size size) { | |
double diameter; | |
if (reclipType == ReclipType.fromWidth) { | |
diameter = size.width / 2; | |
} else { | |
diameter = size.height / 2; | |
} | |
return Rect.fromCenter( | |
center: Offset(size.width / 2, size.height / 2), | |
width: diameter, | |
height: diameter); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment