Search code examples
c#textoverflowpaintpicturebox

How can I write overflowed text to the next line in picturebox?


I am painting to PictureBox but the problem is my painting (text) overflow from picture box. How can I write to the next line?

    private string idbul(string gelenid)
    {
        string id = gelenid;
        string[] malzeme = id.Split(' ');
        string mal_id = malzeme[0];
        mal_id = mal_id.Replace(" ", "");
        return mal_id;
    }
    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        using (Font myFont = new Font("Arial", 8))
        {
            string id = idbul(comboBox1.Text);
            string tanim = tanimbul(comboBox1.Text);
            DateTime now = DateTime.Now;
            string tarih = now.ToString("dd/MM/yyyy");
            e.Graphics.DrawString("SKYLAB TEKNOLOJİ", myFont, Brushes.Black, new Point(2, 145));
            e.Graphics.DrawString("ÜRÜN KODU: " + id, myFont, Brushes.Black, new Point(2, 160));
            e.Graphics.DrawString("Tanım : " + tanim, myFont, Brushes.Black, new Point(2, 175));
            e.Graphics.DrawString("Tarih : "+tarih, myFont, Brushes.Black, new Point(2, 190));

        }
    }
    private string tanimbul(string p)
    {
        string id = p;
        string[] malzeme = id.Split(' ');
        malzeme[0] = "";
        string mal_id = String.Join(" ", malzeme);
        return mal_id;
    }

The string variable "tanim" can be long text so it is overflowing. From the screenshot, you can see the problem.

Screenshot:

enter image description here


Solution

  • In DrawString you can specify the bounding rectangle (kind of like margins) see here

    edit* I looked into it more, the word wrapping only happens for actual words, as in it won't wrap in the middle of a word, only at the end of a word and before the start of the next word.

    You can also try getting the length of the tanim (tanim.Length) and writing a separate DrawString if its longer than what will fit into your box.

    something like this:

    if(tanim.Length>x)
    {
        drawstring("tanim : "+tanim.substring(0,x),font,brush,firstlinestart);
        drawstring(tanim.substring(x),font,brush,secondlinestart);
    }
    

    where x is the number of characters you can have fit onto the first line.