2015-12-28 38 views
5

我想讓我的圖像查看一個圓圈,但它始終以鑽石的形式出現。我認爲這個代碼的工作,但它不是:圓形ImageView作爲鑽石出來

profilePic.layer.cornerRadius = profilePic.frame.width/2 
    profilePic.clipsToBounds = true 
+1

您的圖片視圖的高度和寬度應該相同。那麼它會看起來像圓圈 –

+0

雖然他們是相同的,我在故事板中的寬高比爲1:1。 – cb428

+0

使用profilePic.layer.masksToBounds = YES; –

回答

1

通過將其添加到下面的代碼destinationViewController嘗試在

override func viewWillLayoutSubviews() { 
    super.viewWillLayoutSubviews() 
    profilePic.layer.cornerRadius = profilePic.frame.width/2 
    profilePic.clipsToBounds = true 
} 
+2

堆棧溢出不讓我接受你的答案,但這工作 - 謝謝你! – cb428

+1

我也是同樣的問題之前。我認爲imageview佈局不適合作爲viewdidload中的自動佈局。你不能接受,因爲有人用負面評價來標記它。 – jay

+1

viewWillLayoutSubviews會調用多個時間,以避免,你可以把viewDidLoad中也用下面的方式{讓delayTime = dispatch_time(DISPATCH_TIME_NOW, 的Int64(0.1 *雙(NSEC_PER_SEC))) dispatch_after(delayTime,dispatch_get_main_queue()){ profilePic.layer .cornerRadius = profilePic.frame.width/2 profilePic.clipsToBounds = true }} – jay

0

手動實現init(coder aDecoder: NSCoder!)你的代碼。

初始化你ImageView作爲下

init(coder aDecoder: NSCoder!) { 
    super.init(coder: aDecoder) 
    profiePic = [[UIImageView alloc]init]; 
    profilePic setFrame : CGRectMake ("Set Your Control's Frame here"); 
    profilePic.layer.cornerRadius = profilePic.frame.width/2 
    profilePic.clipsToBounds = true 
} 

你會得到你的願望的結果。

0

這對我的作品

profilePicImageView.layer.cornerRadius = profilePicImageView.frame.size.height/2 
profilePicImageView.layer.masksToBounds = false 
profilePicImageView.clipsToBounds = true 
profilePicImageView.layer.borderWidth = 0 
0

使用相同的代碼在viewDidLayoutSubviews方法或viewDidAppear方法。實際上,根據視圖的生命週期,這些方法按以下方式執行:init,loadView,viewDidLoad,viewWillAppear,viewWillLayoutSubViews,然後應用自動佈局約束最後viewDidAppear

從你的問題看來,你在自動佈局約束得到應用之前將你的代碼放在任何方法中。這就是爲什麼,你沒有獲得適當的視圖寬度,它變成了菱形而不是圓形。

1

您可能無法在每臺設備上都找到完美的圈子,請嘗試將2.0更改爲不同尺寸設備附近的不同值。

-(void)viewDidLoad { 
    self.profilePic.layer.cornerRadius = self.profilePic.frame.size.width/2.0f; 
    self.profilePic.clipsToBounds = YES; 
} 
+0

感謝盧卡斯編輯建議,我的第一個答案在這裏。我感謝您的幫助。 –