How can I find out if the entire text of a label is displayed in Xamarin.Forms

Wei Wen 1,096 Reputation points
2021-05-26T04:04:10.64+00:00

I have a label that may contain very long text. However, I only want to display the first five lines. If there are more text, then they will be truncated. But I want to know if the full text is displayed on the label or not, so that I can add a button below the label that opens a popup to display the full text when clicked. How can I know if the entire text of the label is displayed?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,261 questions
0 comments No comments
{count} votes

Accepted answer
  1. JessieZhang-MSFT 7,706 Reputation points Microsoft Vendor
    2021-05-26T09:30:46.08+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    You can calculate or measure width of a string first on each platform using DependencyService .

    You can pass the text content of label to the native to calculate the width of the string.

    1.define interface in forms app

     public interface CalculateTextWidth { double calculateWidth (string text); }  
    

    2.In Android platform

    public class CalculateTextWidthDroid : ICalculateTextWidth  
    {  
        public CalculateTextWidth_Android() { }  
    
        public double calculateWidth(string text)  
        {  
            Rect bounds = new Rect();  
            TextView textView = new TextView(Forms.Context);  
            textView.Paint.GetTextBounds(text, 0, text.Length, bounds);  
            var length = bounds.Width();  
            return length / Resources.System.DisplayMetrics.ScaledDensity;  
        }  
    }  
    

    For more details, you can check: https://forums.xamarin.com/discussion/67545/how-to-calculate-or-measure-width-of-a-string

    Best Regards,

    Jessie Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful