Reputation: 105
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.
Upvotes: 0
Views: 1286
Reputation: 96
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;
Upvotes: 2