How to put rounded corners to canvas image?

1.4k Views Asked by At

I am drawing an image on Canvas in following manner.

void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint.color = Colors.white;

    canvas.drawImageRect(
        img,
        Rect.fromLTWH(0, 0, img.width.toDouble(), img.height.toDouble()),
        Rect.fromLTWH(0, 0, newImgWidth, newImgHeight),
        paint);
}

I want to give rounded corners to this image.

Can anyone provide some help on how to do something like that?

2

There are 2 best solutions below

0
On

let me give you code sample

void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint.color = Colors.white;

    canvas.clipRRect(
      RRect.fromLTRBAndCorners(0, 0, img.width.toDouble(), img.height.toDouble(),topLeft:20,topRight:20,bottomLeft:20,bottomRight:20); // left, top, right, bottom
    );

    canvas.drawImageRect(
        img,
        Rect.fromLTWH(0, 0, img.width.toDouble(), img.height.toDouble()),
        Rect.fromLTWH(0, 0, newImgWidth, newImgHeight),
        paint);
}

you have to match the coordinates of RRect and the ImageRect that you want to clip

4
On

Lets make a try to use clipRRect() method of Canvas class

Add following code snippet inside your paint() method and change the value 20 with your required radius value

canvas.clipRRect(
  RRect.fromLTRBAndCorners(20, 20, 20, 20); // left, top, right, bottom
);

Full version

void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint.color = Colors.white;

    canvas.clipRRect(
      RRect.fromLTRBAndCorners(20, 20, 20, 20); // left, top, right, bottom
    );

    canvas.drawImageRect(
        img,
        Rect.fromLTWH(0, 0, img.width.toDouble(), img.height.toDouble()),
        Rect.fromLTWH(0, 0, newImgWidth, newImgHeight),
        paint);
}