[Flutter/dart] Cut out the part off the center of the image
Overview
If you want to crop an image in a circle with Flutter, I think you use Circle Avator.
CircleAvator determines the radius and center of the circle to fit the entire image, but you may want to crop it differently.
For example, when cropping a person's photo, it is easier to see only the face part than to reduce it so that the whole body fits in.
Therefore, this time, I will introduce a method to cut out the part off the center of the image like this.
Widget _myImg(){
return CircleAvatar(
child: Image.asset('image/person.png',),
backgroundColor: Colors.transparent,
radius: 50,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
const SizedBox(height: 32,),
Center(
child: _myImg()
)
],
),
);
}
Method
Use ClipOval.
With ClipOval, you can freely decide the position and size of the cutout.
First, create a class that extends CustomClipper (here, MyClipper).
class MyClipper extends CustomClipper<Rect>{
MyClipper();
@override
Rect getClip(Size size) {
return Rect.fromCircle(
center: Offset(size.width/2, size.width/2),
radius: size.width/2
);
}
@override
bool shouldReclip(covariant CustomClipper<Rect> oldClipper) {
return false;
}
}
When extending CustomClipper, you need to implement getClip () and shouldReclip ().
You specify whether the image needs to be cropped again shouldReclip (). I set false always here.
getClip () is a method that specifies the cropping method. The argument size is the size of the original image, and the return value of this method will crop the image.
This time, the vertically long rectangular image is cut out with a circle inscribed on the left side, right side, and top side, so the return value is as shown above.
Then specify an instance of MyClipper in ClipOval's clipper property.
This will crop the image.
Widget _myImg(){
return ClipOval(
clipper: MyClipper(),
child: Image.asset('image/person.png',),
);
}
Lastly
The most important point is to determine the cropping range with getClip. If it is an inscribed circle, I think it can be implemented without much effort.
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
Comments