2017-04-05 77 views
0

有找到一個字符串到PCL項目的長度的方法嗎?我可以使用Application類來獲取設備頁面的寬度和高度,但我不知道如何獲取字符串的度量。如何獲取Xamarin.Forms的PCL字符串的長度?

P.S.我想知道用戶的設備是否可以顯示全文。

+0

'System.String'有一個'Length'屬性,這就是你要找的 – maccettura

+0

你的意思是渲染字符串的像素數? – Jason

+0

@Jason是的,我曾說過像素大小。我需要知道我的設備是否可以將給定的字符串包含到一個屏幕頁面中。 –

回答

1

這需要對自己的每個平臺做,你做一個PCL接口這樣的:

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

,然後例如,在Android的代碼將是這樣的:``公共類CalculateTextWidth_Android: CalculateTextWidth { 公共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; 
    } 

看到此鏈接獲取更多信息和其他平臺實現 how-to-get-the-length-of-a-string-into-pcl-of-xamarin-forms