iOS 計算文字寬度的一個細節

來源:互聯網
上載者:User

標籤:log   code   turned   電腦   大小   nslog   amount   space   ios   

設計師給到的圖,經常是 “按鈕的左邊距離文字右邊5px” 這樣子的標註。於是我們需要計算文字的寬度。
有兩種方法:

  1. 用 label 或 button 的 sizetofit 方法

    [label sizeToFit];NSLog(@"label size is %@",[NSValue valueWithCGSize:label.bounds.size]);
  2. 用 sizeWithAttributes方法

    CGSize size = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];NSLog(@"size WithAttributes is %@",[NSValue valueWithCGSize:size]);  

結果如何呢?

label size is NSSize: {96.5, 20.5}
size WithAttributes is NSSize: {96.39697265625, 20.287109375}

可見兩個傳回值不同,第二種方法返回的值似乎精確,應該用哪個呢?
我們來看下文檔怎麼說的。

  1. 關於 sizeWithAttributes 的文檔

    This method returns fractional sizes; to use a returned size to size views, you must raise its value to the nearest higher integer using the ceil function.

  2. 關於 sizeToFit 的文檔

    Call this method when you want to resize the current view so that it uses the most appropriate amount of space.

在文檔中,明確指出了使用 sizeWithAttributes 時,需要使用 ceil 方法取整。而 sizeToFit 方法會當前 view 的大小調整為 appropriate 大小。
這裡的關鍵是對 appropriate 的理解。我說下我的理解,至少應該滿足兩個條件:

  1. 不截斷
    就是說返回的值應該不小於文字的寬度/長度,否則會被截斷。
  2. 像素對齊
    所有的 view 的起始和結束為止都應該在物理像素上。因此在 @2x 螢幕應該返回 0.5 的整數倍,在 @1x 螢幕上應該返回 1 的整數倍。

因此應該用第二種方法,或者把第一種方法的結果向上取整。
如果直接使用第一種方法的結果,會導致其他介面像素對不齊,有奇怪的表現。
想象一下電腦如何處理 “一條線段,起點是 3.452 像素,終點是 56.341 像素” 這種奇怪的東西。

iOS 計算文字寬度的一個細節

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.