为什么这是不同的? [英] Why this is different?

查看:79
本文介绍了为什么这是不同的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string text = "aaaaaa";
float width1 = e.Graphics.MeasureString(
    text,
    new Font("calibri", 12, GraphicsUnit.Pixel)).Width;

float width2 = 0;
for (int i = 0; i < text.Length; i++)
{
    width2 += e.Graphics.MeasureString(
        text[i].ToString(),
        new Font("calibri", 12, GraphicsUnit.Pixel)).Width;
}



我想测量Chracter的大小。

为什么width2和width1不完全相同?

我怎样才能正确衡量人物?



我尝试过的事情:



这是我最好的主意...我猜。


i want to measure size of Chracter.
why width2 and width1 is not exactly same?
and how can i measure Character rightway?

What I have tried:

this is my best idea... i guess.

推荐答案

因为字符串的宽度不是除了非比例(或固定宽度)字体外,所有字符的宽度。

在固定宽度字体中,所有字符的宽度都相同,因此字符串是字符宽度乘以数字字符:

WIIIIILL

12222234


但是用比例字体:

WIIIIILL

12222234


字符不一样宽度。

这不会导致你的问题,但它开始说明为什么这是一个问题 - 因为比例字体可以有其他功能,如配对字距:

WAWAWA

121212


WAWAWA

121212

这里发生的是W和A被塞在一起因为部分W下的A适合,而不是等待它完成,并添加了一个小差距:

WAWANAWA

(还有其他效果,但这是最容易显示的)

所以你不能只是测量每个字符并假设字符串长度相同!



[edit]为可读性添加换行符[/ edit]
Because the width of a string is not the sum of the widths of all teh characters, except in non-proportional (or fixed width) fonts.
In a fixed width font all characters are the same width, so the string is the width of a character times the number of characters:
WIIIIILL
12222234

But in a proportional font:
WIIIIILL
12222234

The characters aren't the same width.
That doesn't cause your problem, but it starts to indicate why it's a problem - becuase proportional fonts can have other features, such as pair-kerning:
WAWAWA
121212

WAWAWA
121212

What happens here is that the W and the A are "tucked together" because part of the A "fits" under the W instead of waiting for it to finish and a small gap added:
WAWANAWA
(there are other effects as well, but that is the easiest to show)
So you can't just measure each character and assume the string will be the same length!

[edit]line breaks added for readbility[/edit]


这篇关于为什么这是不同的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆