您的位置:首页 > 编程语言 > Qt开发

Qt-文本绘制

2014-03-22 22:59 218 查看
drawtext.h

#ifndef _DRAWTEXT_H_
#define _DRAWTEXT_H_

#include <QWidget>
#include <QPixmap>

class DrawText : public QWidget
{
public:
DrawText( QWidget * = 0 );

protected:
void paintEvent( QPaintEvent * );

private:
int randomInt( int );
int randomInt( int , int );

QPixmap pixmap;
};
#endif


drawtext.cpp

#include "drawtext.h"
#include <QtGui>
#include <cstdlib>

DrawText::DrawText( QWidget *parent )
:QWidget( parent )
{
const int WIDTH = 800;
const int HEIGHT = 600;
const int MAX_FONT_SIZE = WIDTH / 4;
const int MIN_FONT_SIZE = WIDTH / 40;

pixmap = QPixmap( QSize( WIDTH, HEIGHT ) );
pixmap.fill( Qt::white );

QPainter painter( &pixmap );
painter.setRenderHint( QPainter::Antialiasing );

srand( (int) time( NULL ) );

for( int i = 0; i < 20; ++i )
{
QFont font;
int fontSize = randomInt( MIN_FONT_SIZE, MAX_FONT_SIZE );
font.setPixelSize( fontSize );

painter.setFont( font );
painter.setPen( QColor( randomInt( 255 ), randomInt( 255 ), randomInt( 255 ) ) );
painter.drawText( QPoint( randomInt( WIDTH - MAX_FONT_SIZE ),
randomInt(2 * MAX_FONT_SIZE / 3 , HEIGHT) ), QString("Qt") );
}

setWindowTitle( tr( "Draw Text" ) );
setFixedSize( WIDTH, HEIGHT );
pixmap.save( "pixmap.png" );
}

void DrawText::paintEvent( QPaintEvent * )
{
QPainter painter( this );
painter.drawPixmap( QPoint( 0, 0 ), pixmap );
}

int DrawText::randomInt( int high )
{
return randomInt( 0, high );
}

int DrawText::randomInt( int low, int high )
{
double d = (double)rand() / ( (double)RAND_MAX + 1 );
int k = (int) (d * ( high - low + 1 ));

return k + low;
}


main.cpp

#include "drawtext.h"
#include <QApplication>

int main(int argc, char **argv )
{
QApplication app( argc, argv );

DrawText drawText;
drawText.show();

return app.exec();
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: