0
長碼道歉。這是儘可能減少它。如何解決這個舍入誤差?
#include <QtGui/QApplication>
#include <QtGui/QWidget>
#include <QtGui/QImage>
#include <QtGui/QPainter>
#include <vector>
using namespace std;
class View : public QWidget {
typedef pair<double, double> Point;
unsigned char* _buffer;
double centerx, centery, scale;
double xmin, xmax, ymin, ymax;
double xprec, yprec;
double xratio, yratio;
double fwidth, fheight;
double xlen, ylen;
int width;
int height;
public:
View(int w, int h) : width(w), height(h) {
_buffer = new unsigned char[4 * w * h];
fwidth = static_cast<double>(width);
fheight = static_cast<double>(height);
double aspectRatio = fwidth/fheight;
centerx = 0;
centery = 0;
scale = 2.3;
xlen = aspectRatio * scale;
ylen = 1.0 * scale;
xmin = -(xlen * 0.5) + centerx;
xmax = -xmin;
ymin = -(ylen * 0.5) + centery;
ymax = -ymin;
xprec = xlen/fwidth;
yprec = ylen/fheight;
xratio = fwidth/scale/aspectRatio;
yratio = fheight/scale;
}
double roundX(double x) { return std::floor(x/xprec) * xprec; }
double roundY(double y) { return std::floor(y/yprec) * yprec; }
protected:
void paintEvent(QPaintEvent* event) {
QPainter painter(this);
render();
painter.drawImage(
QPoint(0, 0),
QImage(_buffer, width, height, QImage::Format_RGB32));
}
private:
void render() {
memset(_buffer, 0, 4 * width * height);
for (double i = xmin; i < xmax; i += xprec) {
for (double j = ymin; j < ymax; j += yprec) {
Point p(roundX(i), roundY(j));
int x = static_cast<int>((p.first * xratio) - (xmin * xratio));
int y = static_cast<int>((p.second * yratio) - (ymin * yratio));
_buffer[4 * (x * width + y) ] = 255;
_buffer[4 * (x * width + y) + 1] = 255;
_buffer[4 * (x * width + y) + 2] = 255;
}
}
}
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
View view(512, 512);
view.show();
return app.exec();
}
代碼,而不是產生一個白色的窗口,產生一個白色的窗口,其中線是圓的錯誤的結果。我認爲問題的根源是roundX()
和roundY()
函數,但我不確定。我也不知道如何解決這個問題。有任何想法嗎?
還有的四捨五入發生在幾個地方。你的'for'循環作爲*累加*四捨五入。鑑於'View'是用ints構建的,並且像素位置是整數,我建議重新編譯該邏輯,以便浮點值不用於中間值。 –
我建議在整個程序中使用'sizeof(variable)* width * height'而不是'4 * width * height'。 – Nav