画图,处理图像
testqimage.cpp
#include "testqimage.h"
#include <QPainter>
TestQImage::TestQImage(QWidget* parent)
: QWidget(parent)
{
ui.setupUi(this);
img = QImage(1280, 720, QImage::Format_RGBA8888);
//填入颜色
img.fill(QColor(255, 0, 0, 200));
//遍历设置颜色
uchar* data = img.bits();
//假定已对齐,不对齐就出错
for (int i = 0; i < img.width(); i++)
{
for (int j = 0; j < img.height() / 2; j++)
{
data[j * img.width() * 4 + i * 4] = 0;// R
data[j * img.width() * 4 + i * 4 + 1] = 255;// G
data[j * img.width() * 4 + i * 4 + 1] = 0;// B
data[j * img.width() * 4 + i * 4 + 1] = 255;// A
}
}
for (int i = img.width() / 2; i < img.width(); i++)
{
for (int j = 0; j < img.height(); j++)
{
img.setPixelColor(i, j, QColor(0, 0, 255, 255));
}
}
}
void TestQImage::paintEvent(QPaintEvent* ev)
{
QPainter p(this);
if (!img.isNull())
p.drawImage(0, 0, img);
}
画线、画文本
#include "testqpainter.h"
#include <QPainter>
TestQPainter::TestQPainter(QWidget* parent) :QWidget(parent)
{
ui.setupUi(this);
}
void TestQPainter::paintEvent(QPaintEvent* ev)
{
//设置绘制设备 (widget)
QPainter p(this);
//p.begin(this);
//设置画笔颜色
p.setPen(QColor(255, 0, 0, 150));
//设置字体
//p.setFont(QFont(QStringLiteral("黑体"), 30));
QFont font = ui.fontComboBox->currentFont();
font.setPixelSize(30);
p.setFont(font);
//绘制文本
p.drawText(100, 100, QStringLiteral("测试的显示文字"));
//绘制线
//设置画笔样式
QPen pen;
//实线
pen.setStyle(Qt::SolidLine);
//线粗
pen.setWidth(30);
//线刷子
pen.setBrush(Qt::red);
//刷子为图片
//pen.setBrush(QBrush(QImage("test.jpg")));
//结尾端样式
pen.setCapStyle(Qt::RoundCap);
//连接处样式
pen.setJoinStyle(Qt::RoundJoin);
p.setPen(pen);
p.drawLine(QLine(0, 0, 300, 300));
p.drawLine(QLine(300, 300, 600, 0));
QVector<QLine> lines;
lines.push_back(QLine(0, 0, 350, 350));
lines.push_back(QLine(350, 350, 0, 450));
lines.push_back(QLine(0, 450, 550, 550));
p.drawLines(lines);
p.end();
}