テキストを画像の中央に配置するときの私の戦略は、そのテキストの境界長方形を取得し、幅または高さを 2 で割ることです。この場合も同じようにしました。これは私が作成した例です:
void CanvasWidget::paintEvent(QPaintEvent*)
{
//Create image:
QImage image(rect().width(), rect().height(), QImage::Format_RGB32);
QPainter paint(&image);
// White background
image.fill(QColor("#FFF"));
// set some metrics, position and the text to draw
QFontMetrics metrics = paint.fontMetrics();
int yposition = 100;
QString text = "Hello world.";
// Draw gray line to easily see if centering worked
paint.setPen(QPen(QColor("#666"), 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin));
paint.drawLine(0, yposition, image.width(), yposition);
// Get rectangle
QRect fontRect = metrics.boundingRect(text);
// Black text
paint.setPen(QPen(QColor("#000"), 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin));
// Add half the height to position (note that Qt has [0,0] coordinates at the bottom of the image
paint.drawText(4, yposition+round(((double)fontRect.height())/2.0), text);
QPainter p(this);
p.drawImage(rect(), image, image.rect());
p.end();
}
結果は次のとおりです。テキストは行の中央ではなく下に表示されます。
アンドロイド:
Windows:
線を使用して、メトリックの長方形に基づいてテキストの周りにフレームを描画しました。
意図した結果は、指定された点/線を正確に中心に表示テキストを配置することでした:
概観すると、これが私が抱えている実際の
問題です
。数字は線の真ん中にあるはずで、下にある必要はありません。
私が使用している関数は、そこにないアクセントやその他の大きな文字を含むサイズを返します。そこにある文字に対してのみピクセル単位で長方形を取得するにはどうすればよいですか?