Drawtext Multiline

Hi, how can I use multiline text in canvas with SkiaSharp? I want set width of my dynamic text where in the middle of square.

Thank you very much

Best Answer

Answers

  • AloisDenielAloisDeniel FRUniversity ✭✭

    I opened an issue related to this on SkiaSharp.Extented : https://github.com/mono/SkiaSharp.Extended/issues/12

    A naive workaround :

    private void DrawTextArea(SKCanvas canvas, SKPaint paint, float x, float y,  float maxWidth, float lineHeight, string text)
    {
        var spaceWidth = paint.MeasureText(" ");
        var lines = text.Split(new [] { Environment.NewLine }, StringSplitOptions.None);
        lines = lines.SelectMany(l => SplitLine(paint,maxWidth,l,spaceWidth)).ToArray();
    
        for (int i = 0; i < lines.Length; i++)
        {
            var line = lines[i];
            canvas.DrawText(line, x, y, paint);
            y += lineHeight;
        }
    }
    
    private string[] SplitLine(SKPaint paint, float maxWidth, string text, float spaceWidth)
    {
        var result = new List<string>();
    
        var words = text.Split(new[] { " " }, StringSplitOptions.None);
    
        var line = new StringBuilder();
        float width = 0;
        foreach (var word in words)
        {
            var wordWidth = paint.MeasureText(word);
            var wordWithSpaceWidth = wordWidth + spaceWidth;
            var wordWithSpace = word + " ";
    
            if(width + wordWidth > maxWidth)
            {
                result.Add(line.ToString());
                line = new StringBuilder(wordWithSpace);
                width = wordWithSpaceWidth;
            }
            else
            {
                line.Append(wordWithSpace);
                width += wordWithSpaceWidth;
            }
        }
    
        result.Add(line.ToString());
    
        return result.ToArray();
    }
    
  • cinarfoto2cinarfoto2 FRMember ✭✭

    Thank you very much Alois, but its very hard for something about alignment, style. I am not good at Xamarin. If you help me about style I will be really grateful. it seems like 2. png; And I want that it seems like 1.png

    Thank you very much.

    2.png 17.7K
    1.png 132.9K
  • cinarfoto2cinarfoto2 FRMember ✭✭

    Wow! its exactly as I want. Thank you very much!

  • Mat00088Mat00088 USMember ✭✭
    Align left and align right also possible?
Sign In or Register to comment.