1.QImage 填充透明画笔
问题如下:
QImage如何填充一个透明的path
解决1
rect = path.boundingrect();
遍历 rect => (x, y), if(path.contains(x, y)) img.setPixel(x, y, transparent);
这样绘制的画笔会有严重的粗细反差,效果很差
解决2
优化解决1,将path转成对于的list<point>,然后再次setFixel即可
QList<QPoint> Form::path2Points(const QPainterPath &path)
{
QList<QPoint> curPoints;
QRect r = path.boundingRect().toRect();
QImage img(r.x() + r.width(), r.y() + r.height(), QImage::Format_ARGB32);
img.fill(qRgba(255, 255, 255, 255));
QPainter p(&img);
p.fillPath(path, QColor(0, 0, 0, 255));
for(int x = r.x(); x < r.x() + r.width(); x ++) {
for(int y = r.y(); y < r.y() + r.height(); y ++) {
if(img.pixel(x, y) == qRgba(0, 0, 0, 255)
&& img.rect().contains(x, y)) {
curPoints << QPoint(x, y);
}
}
}
return curPoints;
}
2.path.addText如何添加换行
void QPainter::drawText(const QPointF &position, const QString &text)
Draws the given text with the currently defined text direction, beginning at the given position.
This function does not handle the newline character (\n), as it cannot break text into multiple lines, and it cannot display the newline character. Use the QPainter::drawText() overload that takes a rectangle instead if you want to draw multiple lines of text with the newline character, or if you want the text to be wrapped.
By default, QPainter draws text anti-aliased.
Note: The y-position is used as the baseline of the font.
但是path.addText里没有rect的参数,这就很麻烦了
自定义pathText 的函数如下
QPainterPath Form::pathText(int x, int y, QFont font, const QString &text)
{
QPainterPath path;
qreal lineHeight = QFontMetricsF(font).height();
int lineCount = 1;
QByteArray content = text.toUtf8();
QBuffer buff(&content);
buff.open(QBuffer::ReadOnly);
while(!buff.atEnd()) {
QByteArray line = buff.readLine();
path.addText(x, y + lineCount * lineHeight, font, line);
lineCount++;
}
return path;
}