Search code examples
qtdrawimageqpainter

QPainter drawImage becomes very pixelated


I use QPainter and the function drawImage to draw an airplane on a map. The image and redrawn each time the position of the airplane changes. The problem is, after some time, the image becomes extremely pixelated. I have tried to use a high quality .svg and that did not help either.

Below is my code. Can somebody spot where the error is or what has caused the image to be so pixelated?

// Load .svg image
airplane->load("AirplaneTopDown.svg"); 
// Downsize image 
airplaneSmall = airplane->scaled(120, 120,Qt::KeepAspectRatio);
// Rotate image by trans
airplaneSmall = airplaneSmall.transformed(trans);
// Draw image and center at a certain screen position
painter.drawImage(airplaneX-airplaneSmall.width()/2,airplaneY-airplaneSmall.height()/2,airplaneSmall);

Below are the images of the drawn airplanes. One taken as screenshot at the beginning of the program runtime another one taken after a couple of minutes.

Airplane Airplane-pixelated


Solution

  • One of your problems is that you first rescale the image and then rotate it. The rotation needs to interpolate new pixels from the old ones. The higher the resolution of the input, the better the quality of the interpolation. The quality of your SVG is completely lost after the rescale operation.

    The second problem you are facing is that you use the "fast" (default) transformation method. This method does not antialias. So instead of interpolating from several input pixels, it will only take one best fit. Calling transformed() with the second argument Qt::SmoothTransformation and scaled() with the sceond argument Qt::SmoothTransformation |Qt::KeepAspectRatio` will greatly improve your results.

    However it is also slower, as is performing the rotation on the image in its original, higher resolution.

    The arguably best solution to your problem is to take on a different approach. Instead of loading the SVG into a QImage, which is a raster-based image, you should work with the vector graphics. So the SVG is rendered in the right orientation and scale in the first place. A good starting point is the SVG Viewer Example: http://doc.qt.io/qt-5/qtsvg-svgviewer-example.html