简体   繁体   中英

How to put rounded corners to canvas image?

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?

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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM