[英]Qt- How to get the color of a QPoint in QImage for QPixmap
我正在尝试实现泛洪填充算法,该算法需要在每次迭代中获取区域中点的颜色。 但是,即使我已经绘制了一些东西,所选点的颜色也始终是背景色。
void MainWindow::floodFill(QPainter& p, int x, int y, const QColor& cu, const QColor& cc) {
st.push(QPair<int, int>(x, y));
//used for debug
int _r, _g, _b;
int _rCu, _gCu, _bCu;
int _rCc, _gCc, _bCc;
cu.getRgb(&_rCu, &_gCu, &_bCu);
cc.getRgb(&_rCc, &_gCc, &_bCc);
while (!st.isEmpty()) {
QPair<int, int> pair = st.pop();
QPixmap qPix = ui->centralWidget->grab();
QImage image(qPix.toImage());
QColor c(image.pixel(pair.first, pair.second));
//used for debug, here QColor c is always the same
c.getRgb(&_r, &_g, &_b);
if (c == cu || c == cc) {
continue;
}
p.setPen(cu);
p.drawPoint(pair.first, pair.second);
if (pair.first > 0) {
st.push(QPair<int, int>(pair.first - 1, pair.second));
}
if (pair.first < 200/*ui->centralWidget->width()*/) {
st.push(QPair<int, int>(pair.first + 1, pair.second));
}
if (pair.second > 0) {
st.push(QPair<int, int>(pair.first, pair.second - 1));
}
if (pair.second < 200/*ui->centralWidget->height()*/) {
st.push(QPair<int, int>(pair.first, pair.second + 1));
}
}
}
这就是我在绘画比赛中所说的
void MainWindow::paintEvent(QPaintEvent* event) {
QPainter p(this);
QColor colorRed(255, 0, 0);
QColor colorBlack(0, 0, 0);
p.setPen(QPen(colorBlack));
p.drawRect(50, 50, 3, 3);
floodFill(p, 51, 51, colorRed, colorBlack);
}
我认为问题在于:您正在将中央窗口小部件捕获到图像中,但是在其他绘制设备(主窗口本身)中绘制。 我不会在每个paintEvent
调用中都调用grab
,但是您可以尝试使用render
通过这种方式获取图像:
QPixmap qPix(size());
render(&qPix);
QImage image(qPix.toImage());
请注意,您很可能会从Qt( Recursive repaint detected
)收到运行时警告,但是只有一次。 使用grab
应导致无限递归。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.