QT中的3D转换

时间:2017-08-02 16:38:27

标签: c++ qt mingw

我想在QT中编写3D转换。我已经编写了代码来绘制一个立方体。我不知道我应该怎么做才能对翻译,旋转和缩放进行编程。我只找到了矩阵:https://www.tutorialspoint.com/computer_graphics/3d_transformation.htm,但我不知道如何使用它。

#include "widget.h"
#include "ui_widget.h"
#include <iostream>
#include <stdlib.h>
using namespace std;

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget)
{
    img = new QImage(600,600,QImage::Format_RGB32);
    ui->setupUi(this);
    drawCube(200, 300);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::paintEvent(QPaintEvent*)
{
    QPainter p(this);
    p.drawImage(0,0,*img);
}

void Widget::drawCube(int x, int y)
{
    drawLine(x,y,x+100,y);
    drawLine(x,y-100,x+100,y-100);
    drawLine(x+100,y,x+100,y-100);
    drawLine(x,y,x,y-100);
    drawLine(x+50,y-50,x+150,y-50);
    drawLine(x+50,y-150,x+150,y-150);
    drawLine(x+150,y-50,x+150,y-150);
    drawLine(x+50,y-50,x+50,y-150);
    drawLine(x,y,x+50,y-50);
    drawLine(x+100,y,x+150,y-50);
    drawLine(x+100,y-100,x+150,y-150);
    drawLine(x,y-100,x+50,y-150);
}

void Widget::drawLine(int x1, int y1, int x2, int y2)
{
    uchar * bits = img->bits();
    float a,b;
    int x;
    a=(float)(y2-y1)/(x2-x1);
    b=y1-a*x1;
    if(x1>x2)
    {
        swap(x1,x2);
        swap(y1,y2);
    }
    if(y1<=y2)
    {
        for (int y=y1; y<y2; y++)
        {
            if(x1!=x2) x=(y-b)/a;
            else x=x1;
            colorPixel(x,y,bits);
        }
    }
    if(y1>y2)
    {
        for (int y=y2; y<y1; y++)
        {
            if(x1!=x2) x=(y-b)/a;
            else x=x1;
            colorPixel(x,y,bits);
         }
    }
    for (int x=x1; x<x2; x++)
    {
        int y=a*x+b;
        colorPixel(x,y,bits);
    }
}

void Widget::colorPixel(int x, int y, unsigned char * bits)
{
    if (x < 0 || y < 0 || x >= 600 || y >= 600) return;
    int p = x * 4 + y * 600 * 4;
    bits[p] = 255;
    bits[p+1] = 255;
    bits[p+2] = 255;
}

0 个答案:

没有答案