#include "mainwindow.
h"
#include "ui_mainwindow.h"
#include "QColorDialog"
#include "QMouseEvent"
QImage img(500,500,QImage::Format_BGR888);
QColor color = qRgb(255,255,255);
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->label->setPixmap(QPixmap::fromImage(img));
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::dda(float x1,float y1,float x2, float y2)
{
float dx,dy,xinc,yinc,length,x,y;
dx = x2-x1;
dy = y2-y1;
if(abs(dx) >= abs(dy))
{
length = abs(dx);
}
else
{
length = abs(dy);
}
xinc = dx/length;
yinc = dy/length;
int i = 1;
x = x1;
y = y1;
while(i<=length)
{
img.setPixel(x,y,color.rgb());
x += xinc;
y += yinc;
i++;
}
ui->label->setPixmap(QPixmap::fromImage(img));
}
void MainWindow::on_pushButton_clicked()
{
color = QColorDialog::getColor();
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
int x = event->pos().x();
int y = event->pos().y();
if(x>500 || y > 500)
{
return;
}
if(event->button()==Qt::RightButton)
{
VerticesX[numVertices] = VerticesX[0];
VerticesY[numVertices] = VerticesY[0];
dda(VerticesX[numVertices-1],VerticesY[numVertices-
1],VerticesX[0],VerticesY[0]);
}
else
{
VerticesX[numVertices] = x;
VerticesY[numVertices] = y;
if(numVertices > 0)
{
dda(VerticesX[numVertices-1],VerticesY[numVertices-1],x,y);
}
numVertices++;
}
}
void MainWindow::on_pushButton_2_clicked()
{
VerticesX[numVertices] = VerticesX[0];
VerticesY[numVertices] = VerticesY[0];
for(int i=0; i<numVertices; i++)
{
dx = VerticesX[i+1] - VerticesX[i];
dy = VerticesY[i+1] - VerticesY[i];
if(dx==0.0f) slopes[i] = 0.0f;
if(dy==0.0f) slopes[i] = 1.0f;
if(dx!=0 && dy!=0) slopes[i] = dx/dy;
}
for(int y=0; y<500; y++)
{
int k = 0;
for(int i=0; i<numVertices; i++)
{
if((y > VerticesY[i]) && (y <= VerticesY[i+1]) || (y <= VerticesY[i])
&& (y > VerticesY[i+1]))
{
xi[k] = int(VerticesX[i] + slopes[i] * (y-VerticesY[i]));
k++;
}
}
for(int j=0; j<k-1;j++)
{
for(int i=0; i<j-k-1; i++)
{
if(xi[i+1] > xi[i])
{
temp = xi[i+1];
xi[i+1] = xi[i];
xi[i] = temp;
}
}
}
for(int i=0; i<k; i+=2)
{
dda(xi[i],y,xi[i+1]+1,y);
}
}
}