2017-08-24 92 views
0

圓形我如何設置的UIButton的形象,這形象是有邊界圓形我寫相關的代碼,但圖像中適當的圓形不顯示.. 這裏是我的代碼..如何設置UIButton的形象,這形象是與邊界

btnMyProfile.setImage(UIImage(named: "MyDefaultImg.png"), for: .normal) 
    btnMyProfile.imageView?.contentMode = .scaleAspectFit 
    btnMyProfile.imageView?.layer.cornerRadius = (btnMyProfile.imageView?.frame.width)!/2 
    btnMyProfile.imageView?.layer.borderColor = UIColor.blue.cgColor 
    btnMyProfile.imageView?.layer.borderWidth = 2.0 

我的O/p這個樣子的.. enter image description here

但我需要這樣的.. enter image description here

我能爲實現我做我期望的輸出?請幫我..謝謝..先進

回答

2

設置clipsToBounds = true爲您的ImageView

btnMyProfile.imageView.clipsToBounds = true 

或使用

btnMyProfile.imageView.layer.masksToBounds = true 

apple docs

默認情況下,角落半徑並不適用於 層的內容屬性的圖像;它僅適用於背景顏色和層的 邊界。然而,masksToBounds屬性設置爲 真正導致被夾在圓角的內容。

別的另一種選擇使用UIBezierPath

+0

我改變了但沒有效果。 – NiravS

+0

@NiravS - 檢查更新後的答案 –

+0

我將按鈕大小更改爲Square,因此可以看到完美的圓形,但我需要在按鈕中設置小圖像。那我該怎麼辦? – NiravS

0
func roundedImageView(imgView: UIImageView, borderWidth: Float, borderColor: UIColor) 
{ 
    imgView.layer.cornerRadius = imgView.frame.size.width/2 
    imgView.clipsToBounds = true 
    imgView.layer.borderWidth = CGFloat(borderWidth) 
    imgView.layer.borderColor = borderColor.cgColor 
} 
+0

但是我需要大尺寸的按鈕(矩形形狀)這就是爲什麼給圓形形狀圖像視圖 – NiravS

+0

檢查更新碼 –

0

你可以設置你的形象的高度和寬度相同。

20X20,30X30 ..

0

如果你想第二類型的輸出,你應該減少圖像的大小(32×32如40×或),並與其做
btnMyProfile.imageView?.layer.cornerRadius = (btnMyProfile.imageView?.frame.width)!/2
你應該做的

btnMyProfile.imageView?.layer.cornerRadius = image.size.width/2 

你的代碼的其餘部分似乎OK ..

0

我實現d我的期望輸出@Anbu &的幫助也是基於@ A.Jam .. 這裏的答案是本人正確的代碼..

let img = UIImageView(image: #imageLiteral(resourceName: "defaultPhoto")) 
     img.image = img.image?.resizeImageWith(newSize: CGSize(width: 25, height: 25)) 

     btnMyProfile.setImage(img.image, for: .normal) 
     btnMyProfile.imageView?.contentMode = .scaleAspectFit 
     //btnMyProfile.imageView?.setRadius() 
     btnMyProfile.imageView?.layer.cornerRadius = (btnMyProfile.imageView?.frame.width)!/2 
     btnMyProfile.imageView?.layer.borderColor = customeMainBlueColor.cgColor 
     btnMyProfile.imageView?.layer.borderWidth = 2.0 
     btnMyProfile.imageView?.layer.masksToBounds = true 

//someFile.swift 
extension UIImage{ 
//https://stackoverflow.com/questions/42545955/scale-image-to-smaller-size-in-swift3 
    func resizeImageWith(newSize: CGSize) -> UIImage { 

     let horizontalRatio = newSize.width/size.width 
     let verticalRatio = newSize.height/size.height 

     let ratio = max(horizontalRatio, verticalRatio) 
     let newSize = CGSize(width: size.width * ratio, height: size.height * ratio) 
     UIGraphicsBeginImageContextWithOptions(newSize, true, 0) 
     draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize)) 
     let newImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return newImage! 
    } 
} 
0

您應該添加圖片按鈕的背景,並確保的大小按鈕的比例像20 * 20,30 * 30等,並設置相同的角半徑,因爲您已經設置。