简体   繁体   中英

How to get the length of a string into PCL of Xamarin.Forms?

There is the way to find the length of a string into PCL project? I can get the width and the height of a page for my device by using Application class, but I don't know how to get the measurement of a string.

PS I want to know could a user's device display full text or not.

This needs to be done for each platform on its own, you make a PCL interface like this:

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

and then for example on android the code will be like this:``public class CalculateTextWidth_Android : CalculateTextWidth { 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;
    }

see this link for more info and other platforms implementations how-to-get-the-length-of-a-string-into-pcl-of-xamarin-forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM