我必须创建一些图像作为没有自己的图像/图片的文章的占位符。我已经在python中实现了这一点,但我想再次在qt应用程序中编写代码。 python代码正常工作,它看起来像这样:
def createImage(text="Leer", pfad="", bildname="TextBild.jpg", colorname='red'):
offset = 20 # weisses Textfeld um diesen Offset grösser darstellen
bild = Image.new('RGB', (width, height), colorname)
draw = ImageDraw.Draw(bild)
font = ImageFont.truetype("cour.ttf", 20)
w,h = draw.textsize(text, font)
draw.rectangle((((width-w-offset)/2,(height-h-offset)/2),((width+w+offset)/2,(height+h+offset)/2)), fill='white')
draw.text(((width-w)/2,(height-h)/2),text,'black',font)
## print "Erzeuge: " + pfad + os.sep + bildname, "\nPfad:\t"+pfad, "\nBildname:\t"+bildname
bild.save(pfad + os.sep + bildname) if os.path.exists(pfad) else bild.save(bildname)
但是如何在Qt中做到这一点?我知道有QImage,QPainter等,但我找不到一个有用的例子。也许我做一个系统调用来创建一个带有qt应用程序文本的图像。
图片如下所示:
提前感谢每一个有用的提示。
答案 0 :(得分:0)
对于你给出的这个特定图像,这将完成工作:
QImage image(QSize(400,300),QImage::Format_RGB32);
QPainter painter(&image);
painter.setBrush(QBrush(Qt::green));
painter.fillRect(QRectF(0,0,400,300),Qt::green);
painter.fillRect(QRectF(100,100,200,100),Qt::white);
painter.setPen(QPen(Qt::black));
painter.drawText(QRect(100,100,200,100),"Text you want to draw...");
image.save("testImage.png");
答案 1 :(得分:0)
完美!这就是我正在寻找的东西。非常感谢你!
bool createImage(QString text="Leer", QString path="./", QString imageName="TextImage.png", QColor aColor=Qt::red)
{
int width = 1024;
int height = 768;
int offset = 25;
int w = 400;
int h = 200;
QImage image(QSize(width,height),QImage::Format_RGB32);
QPainter painter(&image);
painter.setBrush(QBrush(aColor));
painter.fillRect(QRectF(0,0,width,height),Qt::darkGreen);
qDebug() << (width-w-offset)/2 << "\t" << (height-h-offset)/2 << "\t" << w << "\t" << h;
QRect aRect = QRect( (width-w)/2, (height-h)/2, w, h );
QRect aRectOffset = QRect( (width-w+offset)/2, (height-h+offset)/2, w-(offset/2), h-(offset/2) );
painter.fillRect(QRect(aRect),Qt::white);
painter.setPen(QPen(Qt::black));
painter.setFont(QFont( "Courier", 20) );
painter.drawText(QRect(aRectOffset),text);
QDir aDir = QDir(path);
if ( aDir.mkpath(path) )
return image.save(path + "/" + imageName);
else
return image.save(imageName);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
createImage("Ein einfacher Text\nDer auch mal länger sein kann.", "", "TestBild.png", Qt::green);
return a.exec();
}
我刚刚用上面的代码玩了一下,现在它对我很有帮助。 : - )