2015年9月9日 星期三

製作 Image 的圖變成圓形


將 Image 的圖形由方塊變成圓形時,直覺上會認為由 UIImageView / UIImage,找到其相關的 Attribute 修改。但,事實上這 Attribute 已定義在其 Parent Class 父類別 UIView 中 [1]:

同樣,Image 的 layer 圖層這 Attribute 也被定義在父類別 UIView 中:
若我們要製作圓形的 Image,就要修改 CALayer [2] 這類別下的 cornerRadius 屬性:
由此知道, cornerRaidus 的資料型態 data type 被宣告為 CGFloat (浮點數),但若要製作 Image 為圓形,那其值又該如何設定? 此時理論上我們也會誤以為 Image 大小的屬性會在 UIImageView / UIImage 中宣告,但,這屬性亦在其父類別 UIView 中宣告:
而此 frame 屬性被宣告為:
接著我們往下查看 CGRect 這類別的定義:
再查看 CGSize [5] 的定義:
由此我們知道,要製作圓形的 Image,首先我們要指定 cornerRadius 的值,而這值是由我們現有 Image 的尺寸,由其中心點,畫成圓圈計算得來:

cell.myImage.layer.cornerRadius = cell.myImage.frame.size.width / 2
設定完之後,我們將邊角切掉:

cell.myImage.clipsToBounds = true
這樣圓形的 Image 就製作完成。 後記: 看來很簡單的製作,卻拉雜循序漸進寫了一堆! 若能舉一反三,碰到新的 UI Control 都能循著這思路,把 App 做出來。市面上的書大都只把這 2 行程式碼寫出,就算交代清楚,但怎麼來,對若是初入門的人而言,既使照書上做,頂多也只是學到打字。學 App 製作,不就是要學會如何釣魚,而不是只懂的吃魚嗎? 不過,每本書都各有其優點,都是作者辛苦的精華,在此僅做個補充。 參考: 1. UIView - ClipsToBounds , https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instp/UIView/clipsToBounds 2. CALayer, https://developer.apple.com/library/prerelease/ios/documentation/GraphicsImaging/Reference/CALayer_class/index.html#//apple_ref/swift/cl/c:objc(cs)CALayer 3. UIImageView, https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIImageView_Class/ 4. CGRect, https://developer.apple.com/library/prerelease/ios/documentation/GraphicsImaging/Reference/CGGeometry/index.html#//apple_ref/swift/struct/c:@S@CGRect 5. CGSize, https://developer.apple.com/library/prerelease/ios/documentation/GraphicsImaging/Reference/CGGeometry/index.html#//apple_ref/c/tdef/CGRect

沒有留言:

張貼留言

prettyPrint();