简体   繁体   中英

Flutter - How to rotate an image around the center with Canvas?

I am trying to rotate an ui.Image from the center. I am able to rotate the image but the image is not rotating to the exact angle. I have added the image below...

When I pass 0 as the angle it is working line.

在此处输入图像描述

Now when I pass 90 as the angle you can the issue. The car has rotated more than 90.

在此处输入图像描述

Now when I pass 180 as the angle you can the issue. The car has rotated more than 180.

在此处输入图像描述

Here is my code:

  Future<ui.Image> getUiImage(String assetImageName, double angle) async {
final ByteData assetImageByteData = await rootBundle.load(imageAssetPath);
image.Image baseSizeImage =
    image.decodeImage(assetImageByteData.buffer.asUint8List());
ui.Codec codec =
    await ui.instantiateImageCodec(image.encodePng(baseSizeImage));
ui.FrameInfo frameInfo = await codec.getNextFrame();
var pictureRecorder = ui.PictureRecorder();
Canvas canvas = Canvas(pictureRecorder);

final double r = sqrt(frameInfo.image.width * frameInfo.image.width +
        frameInfo.image.height * frameInfo.image.height) /
    2;
final alpha = atan(frameInfo.image.height / frameInfo.image.width);
final beta = alpha + angle;
final shiftY = r * sin(beta);
final shiftX = r * cos(beta);
final translateX = frameInfo.image.width / 2 - shiftX;
final translateY = frameInfo.image.height / 2 - shiftY;
canvas.translate(translateX, translateY);
canvas.rotate(angle);
canvas.drawImage(frameInfo.image, Offset.zero, Paint());
return pictureRecorder
    .endRecording()
    .toImage(frameInfo.image.width, frameInfo.image.height);}

Please help me solve this.

It is probably because you use degrees whereas the rotate function expects radians. When you plug in 90 radians it becomes the equivalent of 5156.62 degrees (which gives an end effect of rotating the object 116.62 degrees - a litte more than 90 degrees)

To convert angle to radians, multiply the value by pi/180

double radians = angle * pi / 180;

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