Eugeniy  Maksimov
Eugeniy Maksimov

Reputation: 1694

Why Graphics.MeasureString measures Arabic strring incorrectly?

I have an Arabic string, which is result of concatenation of Arabic string and " : 100". This string is measured and drawn incorrectly. Why?

public partial class Form1 : Form {
    string strIncorrectMeasure = "مەھسۇلات باھاسى" + " : " + "100";//"مەھسۇلات باھاسى : 100";
    string strCorrectMeasure = "100 : مەھسۇلات باھاسى";
    Font font = new Font("Oybab tuz", 18);

    public Form1() {
        InitializeComponent();
    }

    void button1_Click(object sender, EventArgs e) {
        var bitmap = new Bitmap(100, 100);
        var graphics = Graphics.FromImage(bitmap);
        StringFormat format = new StringFormat(StringFormatFlags.DirectionRightToLeft | StringFormatFlags.NoFontFallback | StringFormatFlags.NoClip);
        SizeF measuredIcorrectSize = graphics.MeasureString(strIncorrectMeasure, font, 0, format);
        SizeF measuredCorrectSize = graphics.MeasureString(strCorrectMeasure, font);
        MessageBox.Show(string.Format("FirstString : {0}\nSecondString: {1}", measuredIcorrectSize, measuredCorrectSize));
    }
    void Form1_Paint(object sender, PaintEventArgs e) {
        var font = new Font("Oybab tuz", 18);           
        StringFormat format = new StringFormat(StringFormatFlags.DirectionRightToLeft);
        e.Graphics.DrawString(this.strIncorrectMeasure, font, Brushes.Black, new PointF(300, 10), format);
        e.Graphics.DrawString(this.strCorrectMeasure, font, Brushes.Black, new PointF(10, 50));
    }
}

Is is it possible that this problem is caused by this specific font?

Upvotes: 0

Views: 240

Answers (2)

Eugeniy  Maksimov
Eugeniy Maksimov

Reputation: 1694

I have not found a solution. I think, that problem in the font itself. Other fonts works fine.

Upvotes: 0

Loathing
Loathing

Reputation: 5256

I couldn't find the Oybab tuz font. However, using SystemFonts.MenuFont and SystemFonts.DefaultFont, both sizes come out the same.

Using Graphics.MeasureString and the MenuFont returned a value of 162.1289. However, taking a screenshot and measuring the true width in a bitmap editor results in a width of 155 pixels. If you need the true width then you will need to draw the text to a bitmap and then find the bounding rectangle by looking at the pixel values.

Also, you don't need to create a Bitmap to get a Graphics object. Simply call CreateGraphics(). Also, you should be disposing the objects by wrapping them in using statements.

Upvotes: -1

Related Questions