由离散量表示连续量而引起的失真称为走样,用于减轻走样现象的技术成为反走样,游戏中称为抗锯齿。走样是连续图形离散为想想点后引起的失真,真实像素面积不为 零。走样是光栅扫描显示器的一种固有现象,只能减轻,不可避免。
Wu 反走样算法是对距离进行加权的反走样算法。
空间混色原理指出,人眼对某一区域颜色的识别是取这个区域颜色的平均值,Wu 反走样算法原理是对理想直线上的任一点,同时用两个不同亮度等级的相邻像素来表示。
void WUAntiLine(QPainter* painter, QPoint P0, QPoint P1) {
int dx = P1.x() - P0.x();
int dy = P1.y() - P0.y();
double k = static_cast<double>(dy) / dx;
double e = 0.0;
for (int x = P0.x(), y = P0.y(); x < P1.x(); x++) {
qreal intensity = 1.0 - e;
QColor color1(255 * intensity, 255 * intensity, 255 * intensity);
QColor color2(255 * e, 255 * e, 255 * e);
painter->setPen(color1);
painter->drawPoint(x, y);
painter->setPen(color2);
painter->drawPoint(x, y + 1);
e += k;
if (e >= 1.0) {
y++;
e--;
}
}
}
#include <QApplication>
#include <QPainter>
#include <QWidget>
void WUAntiLine(QPainter* painter, QPoint P0, QPoint P1) {
int dx = P1.x() - P0.x();
int dy = P1.y() - P0.y();
double k = static_cast<double>(dy) / dx;
double e = 0.0;
for (int x = P0.x(), y = P0.y(); x < P1.x(); x++) {
qreal intensity = 1.0 - e;
QColor color1(255 * intensity, 255 * intensity, 255 * intensity);
QColor color2(255 * e, 255 * e, 255 * e);
painter->setPen(color1);
painter->drawPoint(x, y);
painter->setPen(color2);
painter->drawPoint(x, y + 1);
e += k;
if (e >= 1.0) {
y++;
e--;
}
}
}
class MyWidget : public QWidget {
public:
MyWidget(QWidget* parent = nullptr) : QWidget(parent) {
setFixedSize(800, 600);
}
protected:
void paintEvent(QPaintEvent* event) override {
Q_UNUSED(event);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
QPoint P0(100, 100);
QPoint P1(500, 500);
WUAntiLine(&painter, P0,P1);
}
};
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
MyWidget widget;
widget.show();
return app.exec();
}